crop image base64 in javascript

To crop an image in base64 format using JavaScript, you can first create an image from the base64 string, draw it onto a canvas element, specify the dimensions of the cropped image on the canvas, and then convert the cropped image back to base64.

Here's an example of how to crop an image:

index.tsx
// replace base64String with your own base64-encoded image string
const base64String = "data:image/png;base64,iVBORw0KG...";

// create an image
const img = new Image();
img.src = base64String;

// set up canvas element
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");

// wait for image to load
img.onload = function() {
  // set the dimensions for the cropped image
  const croppedWidth = 100;
  const croppedHeight = 100;
  
  // set the position for the cropped image
  const croppedX = 50;
  const croppedY = 50;
  
  // draw the cropped image onto the canvas element
  context.drawImage(img, croppedX, croppedY, croppedWidth, croppedHeight, 0, 0, croppedWidth, croppedHeight);
  
  // convert the cropped image on the canvas back to base64
  const croppedBase64String = canvas.toDataURL();
  
  // do something with the cropped image string, such as displaying it on a webpage
};
927 chars
30 lines

In this example, we create an Image object using the base64 string. We then create a canvas element, and specify the dimensions and position for the cropped image on the canvas using the drawImage method. Once the image is drawn onto the canvas, we convert it back to base64 using the toDataURL method, and that's it!

gistlibby LogSnag