Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the image quality while converting a canvas with the "toDataURL" method?

I want to set the quality factor when I encode a canvas element to jpg.

var data = myCanvas.toDataURL( "image/jpeg" ); 

It does not give me a quality option. Is there an alternative library I can use?

Related: what is the default quality setting used by the different browsers?

like image 785
jedierikb Avatar asked Jan 17 '13 16:01

jedierikb


People also ask

What is canvas toDataURL ()?

toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png .

Is canvas toDataURL async?

Yes, images are loaded asynchronously by the browser.

How do I turn a photo into a canvas?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.


1 Answers

The second argument of the function is the quality. It ranges from 0.0 to 1.0

canvas.toDataURL(type,quality); 

Here you have extended information

And I don't think it's possible to know the quality of the image once is converted. As you can see on this feedle the only information you get when printing the value on the console is the type and the image code itself.

Here's a snippet of code I made to know the default value of the quality used by the browser.

    var c=document.getElementById("myCanvas");     var ctx=c.getContext("2d");     ctx.fillStyle="#FF0000";     ctx.fillRect(0,0,150,75);      var url = c.toDataURL('image/jpeg');     var v = 0     for(var i = 0; i < 100; i++ ){          v += 0.01;         x = parseFloat((v).toFixed(2))         var test = c.toDataURL('image/jpeg', x);          if(test == url){             console.log('The default value is: ' + x);         }     } 

Basically I thought that the change on the image itself would be reflected on the base64 string. So the code just try all the possible values on the toDataURL() method and compares the resulting string with the default one. And it seems to work. For chromium I get 0.92.

Here is the working example on a fiddle.

like image 64
limoragni Avatar answered Sep 19 '22 07:09

limoragni