Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas reduces imagesize of Jpeg, but why?

Tags:

html

canvas

When I draw a JPEG-Image to Canvas using drawImage() and after that, using canvas.toDataURL() to make it saveable local (with right mouseclick), then the saved Jpeg-Image has a reduced filesize about 40%. It is only so, when using Jpeg. PNG, GIF (NON-COMPRESSION-FILES) rises up the size. I thought, if I convert a Image-File to Base64 the size grows up to about 130%. So I think the canvas-element has an own integrated compression-functionality? If so, can I deactivate it?

The Code looks like this:

var img = new Image();

img.onload = function () 
{
var width = img.width;
var height = img.height;
context.drawImage(img, 0, 0,width,height);
document.images[0].src = canvas.toDataURL('image/jpeg');//<-size = 30,2 KB (30.990 Bytes)
}
img.src = "http://www.roomeffect.de/pageslices/RSB.jpg"; //<-original file size = 58,5 KB (59.930 Bytes)

I don't know what the problem is?

like image 523
Okyo Avatar asked Dec 28 '22 10:12

Okyo


2 Answers

You can specify the JPEG quality as the second parameter to the toDataURL function. The default quality in Firefox is 0.92 (92%).

https://developer.mozilla.org/en/DOM/HTMLCanvasElement

like image 195
Neil Avatar answered Jan 15 '23 12:01

Neil


It's not a problem. JPG is a lossy format, there's no reason to expect a JPG which is expanded into a bitmap (so you can see it on the screen) to be the same size as a new JPG made from compressing that bitmap again. If you want the original file to be saved, save the original file.

like image 39
robertc Avatar answered Jan 15 '23 12:01

robertc