-1

While uploading images using file upload I have to resize the uploaded image. But unable to get the current selected image height and width. What should I pass to imageCompress function to get the current uploaded image

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;
}
agrm
  • 3,735
  • 4
  • 26
  • 36

1 Answers1

0

I have called the imageCompress function in change event of the upload like to follow

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;
            }
        });