繁体   English   中英

使用文件上传获取当前上传的图片并调整大小

[英]Get the currently uploaded image using file upload and resize it

使用文件上传上传图片时,我必须调整上传图片的大小。 但无法获取当前选中的图片高度和宽度。 我应该将什么传递给 imageCompress function 以获取当前上传的图像

function onSelect(e) {
    for (var i = 0; i < e.files.length; i++) {
        if (e.files[i].rawFile.type.match(/image.*/)) {
            imageCompress(e.files[i], { 'resizeMaxHeight': "800", 'resizeMaxWidth': "800",'resizeQuality': '0.7', 'resizeType': 'image / jpg' });
       }
}
function imageCompress (sourceImgObj, options) {
    debugger
    var outputFormat = options.resizeType;
    var quality = options.resizeQuality * 100 || 70;
    var mimeType = '';
    if (outputFormat !== undefined && outputFormat === 'png') {
        mimeType = 'image/png';
    } else if (outputFormat !== undefined && (outputFormat === 'jpg' || outputFormat === 'jpeg' || outputFormat === 'image/jpg' || outputFormat === 'image/jpeg')) {
        mimeType = 'image/jpeg';
    } else {
        mimeType = outputFormat;
    }

    var maxHeight = options.resizeMaxHeight || 300;
    var maxWidth = options.resizeMaxWidth || 250;

    //unable to get the image height and width
    var height = sourceImgObj.height;
    var width = sourceImgObj.width;

    if (width > height) {
        if (width > maxWidth) {
            height = Math.round(height *= maxWidth / width);
            width = maxWidth;
        }
    } else {
        if (height > maxHeight) {
            width = Math.round(width *= maxHeight / height);
            height = maxHeight;
        }
    }

    var cvs = document.createElement('canvas');
    cvs.width = width; //sourceImgObj.naturalWidth;
    cvs.height = height; //sourceImgObj.naturalHeight;
    var ctx = cvs.getContext('2d').drawImage(sourceImgObj, 0, 0, width, height);
    var newImageData = cvs.toDataURL(mimeType, quality / 100);
    var resultImageObj = new Image();
    resultImageObj.src = newImageData;
    return resultImageObj.src;
}

我在上传的更改事件中调用了 imageCompress function,如下所示

var _URL = window.URL || window.webkitURL;
        $("#files1").change(function (e) {
            debugger
            var file, img;
            if ((file = this.files[0])) {
                img = new Image();
                var objectUrl = _URL.createObjectURL(file);
                img.onload = function () {
                    imageCompress(this, { 'resizeMaxHeight': "800", 'resizeMaxWidth': "800", 'resizeQuality': '0.7', 'resizeType': 'image / jpg' });
                    _URL.revokeObjectURL(objectUrl);
                };
                img.src = objectUrl;
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM