Explain Codes LogoExplain Codes Logo

Use HTML5 to resize an image before upload

html
responsive-design
canvas
blob
Nikita BarsukovbyNikita Barsukov·Oct 12, 2024
TLDR

To resize an image on the client-side before upload, you can use the canvas API in HTML5. This is implemented with a <canvas> element that draws and scales the image data selected via a <input type="file">.

document.getElementById('imageInput').onchange = function(e) { const reader = new FileReader(); reader.onload = function(event) { const img = new Image(); img.onload = function() { let canvas = document.createElement('canvas'); canvas.width = 100; // "One does not simply" resize canvas.height = 100; // "Size does matter" ;-) canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height); console.log(canvas.toDataURL()); // Resized image ready for its catwalk }; img.src = event.target.result; }; reader.readAsDataURL(e.target.files[0]); };

Set the canvas.width and canvas.height to your desired dimensions for the drawImage method, which resizes the image. The canvas.toDataURL() method will then export the resized image in base64 format.

Image resizing detailed walkthrough

To ensure that you resize the images efficiently, consider the following elaborate approach. We'll have some light-hearted moments in the comments to keep the spirits high while crunching code.

Efficient handling of Godzilla-like resolutions

When dealing with images of monstrous sizes, memory consumption and performance are key factors to consider. By using URL.createObjectURL, those pesky large images can be managed more efficiently than the traditional Data URLs

document.getElementById('imageInput').onchange = function(e) { const file = e.target.files[0]; if (file.type.match(/image.*/)) { const img = new Image(); img.onload = function() { // Size reduced! Congratulations, it's a thumbnail. URL.revokeObjectURL(img.src); // Memory gets short-term memory loss }; img.src = URL.createObjectURL(file); } };

Beautify without deforming

Maintaining aspect ratio keeps our images from looking like they've visited the hall of mirrors. When resizing, calculate the new dimensions based on a maximum size limit. Also, calling canvas.toDataURL with image quality parameters gives you control over the output format quality:

// Next stop... Dimension reduction station canvas.toDataURL('image/jpeg', 0.9); // Have it at 90% 'cause perfection is overrated

Canvas, meet blob

If base64 data isn't your jam, you can sift the resized image through a blob. Here's a little utility function to convert canvas data to a blob:

function canvasToBlob(canvas, callback) { canvas.toBlob(function(blob) { callback(blob); }, 'image/jpeg', 0.9); // Blob is the new black }

Uploading an artistic blob

After resizing and blobbing, FormData and XMLHttpRequest (or the dashing fetch) come together to upload the image blob asynchronously. Also, because even perfect code can trip sometimes, error handling is paramount:

function uploadImage(blob) { let formData = new FormData(); formData.append('image', blob, 'image.jpg'); // AJAX to the rescue... } canvasToBlob(canvas, function(blob) { uploadImage(blob); // It's blobs all the way up });

Giving a swirl to orientation and format

Don't want your images giving you twisted angles? Handle orientation by parsing EXIF data before you resize. After giving your image a twist, you can opt to create webp format images using canvas.toDataURL('image/webp') if size optimization is your game.

From zero to image resizing hero

To uncover every stone in the pathway of image resizing and to maintain the visual integrity, let's explore some additional strategies.

Commonplace challenges: Identify and obliterate

Working with HTML5 and the Canvas API, you might stumble upon issues like incorrect mime types, file size limits, or cross-origin policy contests. A few preventive measures can be validating the image type, handling potential errors deftly, and adhering to security restrictions.

Modern JavaScript syntax: Your knight in shining armor

Use async/await syntax to make your code look like a carefully curated art gallery. This can enhance the way you handle file reading, image loading, and the overall upload process:

async function processImage(file) { // Modern art but with async operations... }

Utility functions: The Swiss-army knife of programming

Craft reusable utility functions that cut image dimensions down to size. This paves the way for a uniform image handling procedure across your app.

FormData: More than meets the eye

In situations where a form contains other data too, you could remove the original image from the FormData and replace it with the resized version using the same key to preserve the form's integrity.