resize base64 image in javascript

To resize a base64 image in JavaScript, we can make use of the HTML5 canvas element. The steps involved are:

  1. Create a new image object and set its source as the base64 image.
  2. Create a canvas element and set its dimensions to the desired size of the resized image.
  3. Draw the original image onto the canvas, specifying the new width and height.
  4. Use the canvas.toDataURL() method to convert the resized image back to base64 format.

Here's the code:

index.tsx
// Function to resize a base64 image
function resizeBase64Img(base64, newWidth, newHeight) {
  // Create an image object
  var img = new Image();

  // Set the src attribute to the base64 image
  img.src = base64;

  // Create a canvas element
  var canvas = document.createElement('canvas');

  // Set the canvas dimensions to the new image size
  canvas.width = newWidth;
  canvas.height = newHeight;

  // Draw the image onto the canvas
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, newWidth, newHeight);

  // Convert the canvas back to base64 format
  var resizedBase64 = canvas.toDataURL();

  // Return the resized base64 image
  return resizedBase64;
}

// Usage
var base64Img = 'data:image/png;base64,iVBORw0KGg...'; // your base64 image
var resizedBase64Img = resizeBase64Img(base64Img, 200, 200); // resize to 200x200
847 chars
30 lines

Note: The above code will work only if the base64 image is of a supported format (e.g., PNG, JPEG, GIF).

gistlibby LogSnag