Categories
JavaScript Answers

How to resize a Base64 image in JavaScript without using canvas?

Spread the love

Sometimes, we want to resize a Base64 image in JavaScript without using canvas.

In this article, we’ll look at how to resize a Base64 image in JavaScript without using canvas.

How to resize a Base64 image in JavaScript without using canvas?

To resize a Base64 image in JavaScript without using canvas, we can create an off-screen canvas component.

For instance, we write

const imageToDataUri = (img, width, height) => {
  const canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d");

  canvas.width = width;
  canvas.height = height;

  ctx.drawImage(img, 0, 0, width, height);
  return canvas.toDataURL();
};

to define the imageToDataUri function.

In it, we create a canvas with createElement.

Then we get the canvas with canvas.getContext.

Next, we set the width and height of the canvas to the size we want.

Then we call drawImage to draw the image with the width and height.

And finally we call canvas.toDataURL to return the resized image as a base64 string.

Conclusion

To resize a Base64 image in JavaScript without using canvas, we can create an off-screen canvas component.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.