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

jedierikb picture jedierikb · Jan 17, 2013 · Viewed 71.1k times · Source

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?

Answer

limoragni picture limoragni · Jan 17, 2013

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.