resize base64 iamge in javascript

To resize a base64 image in javascript, you need to first convert the base64 string to an image object, then draw the image onto a canvas element with the desired width and height, and then convert the canvas back to a base64 string. Here's how you can do it:

index.tsx
function resizeBase64Image(base64, width, height) {
  var canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;

  var img = document.createElement("img");
  img.src = base64;

  // wait for image to load
  img.onload = function() {
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    var resizedBase64 = canvas.toDataURL();
    // do something with the resized base64 string
  };
}
458 chars
17 lines

First, we create a canvas element with the desired width and height. Then, we create an image element and set its source to the base64 string. We then wait for the image to finish loading before drawing it onto the canvas with the drawImage() method. Finally, we convert the canvas back to a base64 string with the toDataURL() method.

To use the function, simply call it with the base64 string and the desired width and height:

index.tsx
resizeBase64Image(base64String, 300, 200);
43 chars
2 lines

This will resize the image to a width of 300 pixels and a height of 200 pixels.

gistlibby LogSnag