I am trying to compress image size using JavaScript. but it returns canvas error. below is my code.
var reader = new FileReader();
reader.readAsDat
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 + '
';
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');
}
Original Image
Resized Image
Compressed Image