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:
Decode the base64 image string into an image object.
Draw the decoded image onto a canvas with the desired new dimensions.
Use the canvas toDataURL() method to retrieve the new base64 image string.
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 objectvar img = new Image();
img.onload = function() {
// Create a canvas with the desired new dimensionsvar canvas = document.createElement('canvas');
canvas.width = 200; // new width canvas.height = 200; // new height// Draw the decoded image onto the canvasvar ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Retrieve the new base64 image stringvar 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