4

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Okyo
  • 357
  • 4
  • 17

3 Answers3

5

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

Neil
  • 54,642
  • 8
  • 60
  • 72
  • 2
    thanx for quick response, but that doesnt solve the problem, the filesize still gets reduced! Doenst matter wich comp-quality I specify. – Okyo Dec 04 '11 at 01:41
4

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.

robertc
  • 74,533
  • 18
  • 193
  • 177
  • "...compressing that bitmap again" ? So does canvas compress that bitmap by its own? base64 is no compression-algo. What disturbs me, is the compressionsize of about 50% thats not good at all. – Okyo Dec 04 '11 at 12:35
  • @Okyo If you're seeing an image on the screen then it is currently not compressed. Why is a compression size of 50% not good? The whole point of compression is to make things smaller. – robertc Dec 04 '11 at 18:32
  • yeah thats actually right, what you are saying, but my intention was just to understand the technique behind this issue. anyhow thanx for support! – Okyo Dec 05 '11 at 00:14
3

This should give you the best results:

document.images[0].src = canvas.toDataURL('image/jpeg', 1);

Quoted from MDN:

If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality.

Pierre
  • 18,643
  • 4
  • 41
  • 62