jedierikb
jedierikb

Reputation: 13079

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?

Upvotes: 48

Views: 92416

Answers (4)

ayu.sheee
ayu.sheee

Reputation: 91

If you are looking for improving quality for canvas.toDataUrl() in fabricJS for format: 'png' then use property 'multiplier' for the same. This is specific for PNG format only. Please checkout the below code

 const dataURL = canvas.toDataURL({
    width: canvas.width,
    height: canvas.height,
    left: 0,
    top: 0,
    format: "png",
    multiplier: 2
  });

Upvotes: 3

Luis Lobo
Luis Lobo

Reputation: 859

const fullQuality = canvas.toDataURL('image/jpeg', 1.0);
const mediumQuality = canvas.toDataURL('image/jpeg', 0.5);
const lowQuality = canvas.toDataURL('image/jpeg', 0.1);

// output: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ…9oADAMBAAIRAxEAPwD/AD/6AP/Z"

Setting image quality with jpegs | MDN

Upvotes: 0

Chuck Le Butt
Chuck Le Butt

Reputation: 48758

Using Fabric.js, a very simple and human-readable way, is this:

canvas.toDataURL({
   format: 'jpeg',
   quality: 0.8
});

This also allows you to have other options, giving you the ability to crop the image, etc:

canvas.toDataURL({
    format: 'png',
    left: 300,
    top: 250,
    width: 200,
    height: 150
})

jsFiddle: http://jsfiddle.net/7f9bqs00/30/

Upvotes: 7

limoragni
limoragni

Reputation: 2776

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.

Upvotes: 86

Related Questions