Question

I am trying to get dataUrl from <canvas> element using canvas.toDataURL(). By default, it returns image/png, but some browsers support the image/jpeg filetype.

How can i detect if a browser supports image/jpeg?

Was it helpful?

Solution

You just specify that you want JPEG like this:

var quality = 0.8;
var dataUri = canvas.toDataURL('image/jpeg', quality); // quality is optional

If your dataUri now contains the same string JPEG is supported. Otherwise the string will be image/png.

if (dataUri.match('image/jpeg')) {
    // support jpeg
}

That being said, I don't think there is any browser which do not support the jpeg format. A test like this is better suited for more uncommon formats in various degrees such as webp, bitmap etc.

For a general test you could do:

function hasSupport(mime) {
    var canvas = document.createElement('canvas');
    canvas.width = canvas.height = 1;
    var uri = canvas.toDataURL(mime);
    return (uri.match(mime) !== null);
}

OTHER TIPS

Per the HTML5 spec at https://www.w3.org/TR/html5/scripting-1.html#the-canvas-element:

When trying to use types other than "image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".)

Therefore you can check like this:

var type = 'image/jpeg';
var data = canvas.toDataUrl(type);

if ( /^data:image\/png[,;]/.test(data) ) {
  type='image/png';
} else if ( /^data:,/.test(data) ) {
  type = null; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top