file
input:// A file input<input type="file" id="upload" />;// Get the selected fileconst image = document.getElementById('upload').files[0];
image
file to ratio
of percentages:const resize = function (image, ratio) {return new Promise(function (resolve, reject) {const reader = new FileReader();// Read the filereader.readAsDataURL(image);// Manage the `load` eventreader.addEventListener('load', function (e) {// Create new image elementconst ele = new Image();ele.addEventListener('load', function () {// Create new canvasconst canvas = document.createElement('canvas');// Draw the image that is scaled to `ratio`const context = canvas.getContext('2d');const w = ele.width * ratio;const h = ele.height * ratio;canvas.width = w;canvas.height = h;context.drawImage(ele, 0, 0, w, h);// Get the data of resized image'toBlob' in canvas? canvas.toBlob(function (blob) {resolve(blob);}): resolve(dataUrlToBlob(canvas.toDataURL()));});// Set the sourceele.src = e.target.result;});reader.addEventListener('error', function (e) {reject();});});};
toBlob
method. If not, we have to get the data URL from canvas.toDataURL()
first, and then use the following function to convert it to a Blob:const dataUrlToBlob = function (url) {const arr = url.split(',');const mime = arr[0].match(/:(.*?);/)[1];const str = atob(arr[1]);let length = str.length;const uintArr = new Uint8Array(length);while (length--) {uintArr[length] = str.charCodeAt(length);}return new Blob([uintArr], { type: mime });};
// Resize image to 50%resize(image, 0.5).then(function (blob) {// Preview// Assume that `previewEle` represents the preview image elementpreviewEle.src = URL.createObjectURL(blob);});