resize and crop image base64 in javascript in javascript

To resize and crop an image encoded in base64 using JavaScript, you can follow the following steps:

  1. Decode the base64 image string into an image object.
  2. Draw the decoded image onto a canvas with the desired new dimensions.
  3. Use the canvas toDataURL() method to retrieve the new base64 image string.
  4. If necessary, further crop the canvas using the context2D.drawImage() method and repeat step 3.

Here's some code that demonstrates these steps:

index.tsx
// Decode the base64 image string into an image object
var img = new Image();
img.onload = function() {
  // Create a canvas with the desired new dimensions
  var canvas = document.createElement('canvas');
  canvas.width = 200; // new width
  canvas.height = 200; // new height

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

  // Retrieve the new base64 image string
  var newBase64 = canvas.toDataURL();

  // If necessary, crop the canvas further
  // e.g., crop left half of the image
  ctx.drawImage(canvas, 0, 0, canvas.width / 2, canvas.height, 0, 0, canvas.width / 2, canvas.height);
  var newCroppedBase64 = canvas.toDataURL();

  // Use newBase64 or newCroppedBase64 as needed
};
img.src = 'data:image/png;base64,iVBORw0KG...'; // replace with your base64 image string
871 chars
24 lines

gistlibby LogSnag