How can I stop the alpha-premultiplication with canvas imageData?

梦想的初衷 提交于 2019-11-27 08:42:14

Bleh, this is an acknowledged issue as far as the canvas spec is concerned. It notes:

Due to the lossy nature of converting to and from premultiplied alpha color values, pixels that have just been set using putImageData() might be returned to an equivalent getImageData() as different values.

So this:

var can = document.createElement('canvas');
var ctx = can.getContext('2d');
can.width = 1;
can.height = 1;
var img = ctx.createImageData(1, 1);
img.data[0] = 40;
img.data[1] = 90;
img.data[2] = 200;
var ALPHAVALUE = 5;
img.data[3] = ALPHAVALUE;
console.log(img.data); 
ctx.putImageData(img, 0, 0);
console.log(ctx.getImageData(0, 0, 1, 1).data); 

outputs:

[40, 90, 200, 5]
[51, 102, 204, 5]

In all browsers.

So this is a lossy operation, there's no workaround unless they change the spec to give an option for not using premultiplication. This was discussed as far back as 2008 in the WHATWG mailing list, and they decided that a "round trip"/identity of put/get image data is not a promise the spec is willing to demand.

If you need to "save" the image data, you can't save it and keep the same fidelity using putImageData. Workarounds by drawing the full-alpha data to a temporary canvas and redrawing to the main canvas with a smaller globalAlpha won't work, either.

So you're out of luck. Sorry.


To this day (May 12, 2014) this still gets discussed on the WHATWG list: http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2014-May/296792.html

Well this is still a bummer...

I supposed if you're using it in a texture for webgl you could just pass it as a uniform byte array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!