← Back toHTML DOM

Resize an image

Written byPhuoc Nguyen
Created
15 Mar, 2020
Last updated
08 Apr, 2020
Category
Level 2 — Intermediate
Contributors
llevequeblup
Assume that we want to resize an image to a given number of percentages. The image can be determined from a `file` input:
js
// A file input
<input type="file" id="upload" />;

// Get the selected file
const image = document.getElementById('upload').files[0];
The following function scales an `image` file to `ratio` of percentages:
js
const resize = function (image, ratio) {
return new Promise(function (resolve, reject) {
const reader = new FileReader();

// Read the file
reader.readAsDataURL(image);

// Manage the `load` event
reader.addEventListener('load', function (e) {
// Create new image element
const ele = new Image();
ele.addEventListener('load', function () {
// Create new canvas
const 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 source
ele.src = e.target.result;
});

reader.addEventListener('error', function (e) {
reject();
});
});
};
In the sample code above, after drawing a new image, we have to check if the current browser supports the canvas' `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:
js
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 });
};
As soon as we have the Blob of the resized image, we can preview it on the front-end or send it to the back-end as a part of FormData:
js
// Resize image to 50%
resize(image, 0.5).then(function (blob) {
// Preview
// Assume that `previewEle` represents the preview image element
previewEle.src = URL.createObjectURL(blob);
});

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn