简体   繁体   English

如何在 JavaScript 中压缩图像大小?

[英]How to compress image size in JavaScript?

I am trying to compress image size using JavaScript.我正在尝试使用 JavaScript 压缩图像大小。 but it returns canvas error.但它返回画布错误。 below is my code.下面是我的代码。

 var reader = new FileReader();
        reader.readAsDataURL(fileItem._file);
        reader.onload = function (event) {
            var base64 = event.target.result.substring(event.target.result.indexOf(',') + 1, event.target.result.length);
     var cvs = document.createElement('canvas');
            var source_img_obj = event.target.result;
            cvs.width = source_img_obj.naturalWidth;
            cvs.height = source_img_obj.naturalHeight;
            var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
            var newImageData = cvs.toDataURL(type, 70 / 100);
            var result_image_obj = new Image();
            result_image_obj.src = newImageData;
            console.log(result_image_obj);
};

Error:错误: 在此处输入图像描述

I think you are looking something like this~我觉得你看起来像这样~

Update This implementation has two methods to reduce the size of the image.更新这个实现有两种方法来减小图像的大小。 One method resize the image the other method compress the image maintaining the same size but it reduces the quality.一种方法调整图像大小,另一种方法压缩图像保持相同的大小,但会降低质量。

 //Console logging (html) if (!window.console) console = {}; var console_out = document.getElementById('console_out'); var output_format = "jpg"; console.log = function(message) { console_out.innerHTML += message + '<br />'; console_out.scrollTop = console_out.scrollHeight; } var encodeButton = document.getElementById('jpeg_encode_button'); var encodeQuality = document.getElementById('jpeg_encode_quality'); function previewFile() { var preview = document.getElementById('source_image'); var previewCompress = document.getElementById('result_compress_image'); var file   = document.querySelector('input[type=file]').files[0]; var reader  = new FileReader(); reader.addEventListener("load", function(e) { preview.src = e.target.result; preview.onload = function() { resizeFile(this, preview); compressFile(this, previewCompress) }; // preview.src = reader.result; }, false); if (file) {  reader.readAsDataURL(file); } } function resizeFile(loadedData, preview) { console.log(loadedData.width + ' ' + loadedData.height); var canvas = document.createElement('canvas'), ctx; canvas.width = Math.round(loadedData.width / 2); canvas.height = Math.round(loadedData.height / 2); var resizedImage = document.getElementById('result_resize_image'); resizedImage.appendChild(canvas); // document.body.appendChild(canvas); ctx = canvas.getContext('2d'); ctx.drawImage(preview, 0, 0, canvas.width, canvas.height); } function compressFile(loadedData, preview) { console.log('width: ' + loadedData.width + ' height: ' + loadedData.height); var result_image = document.getElementById('result_compress_image'); var quality = parseInt(encodeQuality.value); console.log("Quality >>" + quality); console.log("process start..."); var time_start = new Date().getTime(); var mime_type = "image/jpeg"; if (typeof output_format !== "undefined" && output_format == "png") { mime_type = "image/png"; } var cvs = document.createElement('canvas'); cvs.width = loadedData.width; cvs.height = loadedData.height; var ctx = cvs.getContext("2d").drawImage(loadedData, 0, 0); var newImageData = cvs.toDataURL(mime_type, quality / 100); var result_image_obj = new Image(); result_image_obj.src = newImageData; result_image.src = result_image_obj.src; result_image.onload = function() {} var duration = new Date().getTime() - time_start; console.log("process finished..."); console.log('Processed in: ' + duration + 'ms'); }
 <input type="file" onchange="previewFile()"><br> <div> <h3>Original Image</h3> <img id="source_image" /> </div> <div> <h3>Resized Image</h3> <div id="result_resize_image"> </div> </div> <div> <h3>Compressed Image</h3> <img id="result_compress_image" class='img_container' /> </div> <br><br> <div> <fieldset> <legend>Compressor settings</legend> <div id='controls-wrapper'> Compression ratio : <input id="jpeg_encode_quality" size='3' readonly='true' type="text" value="30" /> % </div> </fieldset> </div> <div> <fieldset> <legend>Console output</legend> <div id='console_out'></div> </fieldset> </div>

You might have to resize the canvas size您可能需要调整画布大小

refer the following example here请在此处参考以下示例

function resizeImg(base, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var context = canvas.getContext("2d");
    var deferred = $.Deferred();
    $("<img/>").attr("src", "data:image/gif;base," + base).load(function() {
        context.scale(width/this.width,  height/this.height);
        context.drawImage(this, 0, 0); 
        deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));               
    });
    return deferred.promise();    
}

To compress a File (got from input type file) you can use this function.要压缩文件(从输入类型文件获得),您可以使用此功能。 Just call it with the file, and it will return the same file but compressed:只需使用文件调用它,它将返回相同的文件但已压缩:

const compressImage = (imageFile, quality) => {
    return new Promise((resolve, reject) => {
        const $canvas = document.createElement("canvas");
        const image = new Image();
        image.onload = () => {
            $canvas.width = image.width;
            $canvas.height = image.height;
            $canvas.getContext("2d").drawImage(image, 0, 0);
            $canvas.toBlob(
                (blob) => {
                    if (blob === null) {
                        return reject(blob);
                    } else {
                        resolve(blob);
                    }
                },
                "image/jpeg",
                quality / 100
            );
        };
        image.src = URL.createObjectURL(imageFile);
    });
};

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

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