2

I'd like to resize uploaded images in browser. I am using canvas to draw the uploaded image to canvas and then resize it, and use the result from toDataURL method.

Simplified code (without upload parts) looks something like this:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d', { alpha: false} );
// img src contains data url of uploaded image
ctx.drawImage(img, 0, 0, imgWidth, imgHeight); 
var dataUrl = canvas.toDataURL('image/png');

The problem is dataUrl contains alpha channel, although context was created with alpha set to false.

Is it possible to get data url without the alpha channel?

If not, I considered using one of Javascript image libraries, but most of them rely on canvas.

Also, I could encode the image using data in canvas, but I'd rather not do that :)

nutrija
  • 317
  • 2
  • 8

1 Answers1

5

alpha:false is only used in WebGL. It's ignored when creating a 2d context.

But you can export the canvas in jpg format where your unwanted alpha is eliminated:

// export a full-quality jpg dataUrl

canvas.toDataURL("image/jpeg", 1.0);
markE
  • 102,905
  • 11
  • 164
  • 176
  • 1
    Thanks, that's useful info! Just forgot to mention in question that png format is required. I guess that's not possible with toDataURL method. – nutrija Jan 14 '15 at 16:47
  • 1
    Well, I guess you could create a new Image() using the .jpg dataUrl as its src. Then drawImage that non-transparent image to the canvas. Then .toDataURL('image/png') a second time to get the alpha flattened dataUrl. One possible problem is that the browser is allowed to alpha & gamma correct canvas drawings, so it's possible that some alpha is re-introduced during the second .drawImage. Try it and see if it fits your needs. Good luck with your project! :-) – markE Jan 14 '15 at 16:59