前端上传图片-预览/压缩/上传进度度(附注释完整代码)

   流程如图所示:

前端上传图片-预览/压缩/上传进度度(附注释完整代码)_第1张图片

关键压缩算法如下:

//可选选项
var ops = {
    width: 500,  //最大宽
    height: 500,  //最大高
    quality: 0.92,  //压缩质量
    convertType: "dataURL", //dataURL 或者 blob
    fileType: "png", //文件类型
}

/**
 * [compressImg description]
 * @param  {File}   file     [description]
 * @param  {Function} callback [用于后续处理]
 * @param  {Object}   ops      [压缩选项]
 * @return {Undefined}            [description]
 */
function compressImg(file, callback, ops) {
    var maxWidth = ops.width || 500 //最大尺寸
    var maxHeight = ops.height || 500 //最大尺寸
    quality = ops.quality || 0.92

    var reader = new FileReader()
    var img = new Image()

    img.onload = () => {
        //原始尺寸
        var originWidth = img.width;
        var originHeight = img.height;
        //实际尺寸
        var targetWidth = originWidth
        var targetHeight = originHeight;
        // 图片尺寸超过最大的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽,按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
        }

        var canvas = document.createElement('canvas');  //创建canvas容器
        var context = canvas.getContext('2d');
        canvas.width = targetWidth   //宽高等于图片宽高
        canvas.height = targetHeight //
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight);

        //压缩后传给回调函数
        if (ops.convertType === "dataURL") {
            callback(canvas.toDataURL(), file.name)
        } else if (ops.convertType === "blob") {
            canvas.toBlob(function(blob) {
                callback(blob, file.name)
            }, "image/" + ops.fileType, ops.quality)
        }

    }
    reader.onload = (e) => {
        img.src = e.target.result // 文件base64化,以便获知图片原始尺寸
    }
    reader.onabort = () => console.log('file reading was aborted');
    reader.onerror = () => console.log('file reading has failed');

    //根据MIME类型读取图片
    if (file.type.indexOf("image") !== -1) {
        reader.readAsDataURL(file);
    } else {
        console.log(new Error("输入类型不是图片"))
        return
    }
}

完整Demo:




	
	
	Image compress and preview
		
		
	

	
		
		

		

		
拖动图片至此,或点击

你可能感兴趣的:(前端上传图片-预览/压缩/上传进度度(附注释完整代码))