Reputation: 399
I have a function written in javascript that rotates an image by the given input degree using canvas
I don't know what to try in order to improve image quality.
In this function given below, I give the first argument as a base64 image, the second argument is the degree to which the image should be rotated, the third argument is a callback function.
//code for rotating image.
export const rotateImage = (imageBase64, rotation, cb) => {
var img = new Image();
img.src = imageBase64;
img.onload = () => {
var canvas = document.createElement("canvas");
canvas.width = img.height;
canvas.height = img.width;
var ctx = canvas.getContext("2d");
ctx.translate( Math.floor(img.height/2),Math.floor(img.width/2));
ctx.rotate(rotation * (Math.PI / 180));
ctx.drawImage(img, -img.width / 2, -img.height / 2);
cb(canvas.toDataURL("image/jpeg"))
};
};
Expected result: I want the image rotated without losing image quality at all.
Actual result: After rotating an image size of 550kb it returns an image of size 80 kb. the image quality decreases drastically. how can I rotate this image in such a way that if I rotate a 550kb image by 90 degrees, the quality of the rotated image is 550kb as well?
Thank you for your time. really appreciate it.
Upvotes: 0
Views: 2251
Reputation: 137
Set the quality parameter to 1.
cb(canvas.toDataURL("image/jpeg",1));
Also, I would go for PNG since it is a lossless file format.
cb(canvas.toDataURL("image/png",1));
Upvotes: 1
Reputation: 673
jpeg is lossy, as a mitigation you could try raising the quality. You might be able to raise the quality and end up with a larger jpeg than before.
According to Mozilla's documentation the default is 0.92 https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
I think you should try a quality of 1 and see what you get.
cb(canvas.toDataURL("image/jpeg",1))
You mention not using the resulting image in a browser. Some uses of JPEG support a tagged orientation. I can't recommend any tools to try, but take a look at https://www.impulseadventure.com/photo/exif-orientation.html
ctx.drawImage(img, -img.width / 2, -img.height / 2);
Are you sure this line isn't resizing the image to half of its size?
Upvotes: 1