在上传之前使用url预览来调整图像的大小

时间:2019-03-01 09:21:13

标签: jquery jquery-ui jquery-plugins jquery-ui-resizable resize-image

大家好,我有这个html:

<div>
    <img src="" alt="" id="artwork-image">
</div>

我的js:

        var img = new Image();
        img.src = params.artworkImgUrl;
        var reader = new FileReader();
        // Set the image once loaded into file reader
        reader.onload = function(e) {

            var img = document.createElement("img");
            img.src = params.artworkImgUrl;

            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);

            var MAX_WIDTH = 400;
            var MAX_HEIGHT = 400;
            var width = img.width;
            var height = img.height;

            if (width > height) {
                if (width > MAX_WIDTH) {
                    height *= MAX_WIDTH / width;
                    width = MAX_WIDTH;
                }
            } else {
                if (height > MAX_HEIGHT) {
                    width *= MAX_HEIGHT / height;
                    height = MAX_HEIGHT;
                }
            }
            canvas.width = width;
            canvas.height = height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);

            dataurl = canvas.toDataURL(file.type);
            document.getElementById('artwork-image').src = dataurl;
        };

这个想法是从url(在这种情况下为params.artworkImgUrl)中获取图像,然后调整图像的大小并将图像的大小调整为div artwork-image,我没有遇到一些错误,但是不能正常工作预期。你能提供一些想法吗?提前谢谢,对不起我的英语。

0 个答案:

没有答案