resize image base64 in javascript

You can resize an image in base64 format using javascript by converting it to an image element, drawing it onto a canvas, resizing the canvas, and then converting the canvas back to a base64 string. Here is the code to achieve this:

index.tsx
function resizeBase64Img(base64, width, height) {
    return new Promise((resolve, reject) => {
        // create an image element
        const img = new Image();
        img.src = base64;
        img.onload = () => {
            // create a canvas element
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            // set canvas dimensions
            canvas.width = width;
            canvas.height = height;

            // draw the image onto the canvas
            ctx.drawImage(img, 0, 0, width, height);

            // convert canvas back to base64 string
            const resizedBase64 = canvas.toDataURL();
            resolve(resizedBase64);
        };
        img.onerror = (err) => reject(err);
    });
}
784 chars
25 lines

You can call the resize function like this:

index.tsx
const base64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...";
const width = 300;
const height = 200;

resizeBase64Img(base64, width, height)
  .then(resizedBase64 => console.log(resizedBase64))
  .catch(err => console.error(err));
241 chars
8 lines

This function returns a promise that resolves with the resized base64 string.

gistlibby LogSnag