Sometimes, we want to rotate a base 64 image by X degrees and return new base64 image with JavaScript.
In this article, we’ll look at how to rotate a base 64 image by X degrees and return new base64 image with JavaScript.
How to rotate a base 64 image by X degrees and return new base64 image with JavaScript?
To rotate a base 64 image by X degrees and return new base64 image with JavaScript, we can put the image in a canvas.
Then we do the rotation in the canvas and return the image.
For instance, we write:
<img>
to add an img element.
Then we write:
const img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAARElEQVR42u3PMREAAAgEIE1u9DeDqwcN6FSmHmgRERERERERERERERERERERERERERERERERERERERERERERERERkYsFbE58nZm0+8AAAAAASUVORK5CYII='
const rotateBase64Image = (base64data) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const image = new Image();
image.src = base64data;
return new Promise(resolve => {
image.onload = () => {
ctx.translate(image.width, image.height);
ctx.rotate(45 * Math.PI / 180);
ctx.drawImage(image, 0, 0);
resolve(canvas.toDataURL())
};
})
}
(async () => {
const rotatedImg = await rotateBase64Image(img)
const imgEl = document.querySelector('img')
imgEl.src = rotatedImg
})()
to define the rotateBase64Image
function to rotate the base64data
image by 45 degrees.
In it, we create a canvas with `createElement.
Then we get its context with getContext
.
Next, we create a new Image
instance and set its src
property to base64data
to load the image.
Then when the image is loaded, image.onload
is run.
In onload
, we rotate the image with rotate
.
And we draw the rotated image with drawImage
.
Finally, we call resolve
with the base64 string version of the rotated image that we get from canvas.toDataURL
.
Next, in the async
function, we get call rotateBaseImage
to rotate img
.
Then we select the img element with querySelector
.
And then we set imgEl.src
to the rotateImg
string.
Now we see the pink square rotated 45 degrees.
Conclusion
To rotate a base 64 image by X degrees and return new base64 image with JavaScript, we can put the image in a canvas.
Then we do the rotation in the canvas and return the image.