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

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

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;
}
评论