如何从js中的透明像素获取rgb [英] How to get rgb from transparent pixel in js
问题描述
我有完全透明的图像,我想获取每个像素的rgb数据. 将其视为隐藏的图片.
I have completely transparent image and i want to get rgb data for each pixel. Think of it as a hidden picture.
在javascript中处理图像数据的常用方法是
The usual approach of manipulating image data in javascript is
ctx.drawImage(img, 0, 0);
但是,如果我在绘制后访问画布数据,则所有像素均为黑色.我已经确认可以使用GD GD使图片可见.
However if i access the canvas data after the draw, all of the pixels are black. I have verified that i can make the picture visible with php GD.
关于如何在js中执行操作的任何想法?
Any ideas on how to do it in js?
我知道我可以得到一个直接解析图像数据的js库,但是我正在寻找一种具有库的解决方案.
i know that i could get a js library that directly parses image data but i am looking for a solution withoult libraries.
推荐答案
在canvas API中,每个alpha为0的像素都被视为黑色透明像素.
In canvas API, every pixel with an alpha of 0 is treated as black transparent pixel.
var c = document.createElement('canvas');
var ctx = c.getContext('2d');
c.width = c.height = 1;
ctx.fillStyle = 'rgba(0,255,0,0)'
ctx.fillRect(0,0,1,1)
var i = ctx.getImageData(0,0,1,1)
console.log('after fillRect:',i.data);
i.data[2] = 255;
ctx.putImageData(i,0,0);
console.log('after putImageData', ctx.getImageData(0,0,1,1).data);
console.log('passed imageData', i.data);
i.data[3] = 1;
ctx.putImageData(i,0,0);
console.log('after non transparent', ctx.getImageData(0,0,1,1).data);
这是因为,对于性能而言,浏览器会按照putImageData
设置为透明黑色.
This is because, for performances, browsers do pre-multiply the colors as greatly explained in pleup's answer, which, in this case, allows it to completely omit transparent pixels in drawing operations, and to only set it to transparent black for putImageData
.
无论如何,即使您能够将颜色设置为非黑色透明像素,导出方法也可能会将其重新转换为透明黑色像素.
Any way, even if you were able to set colors to non black transparent pixels, the export methods would probably reconvert it back to transparent black ones.
这篇关于如何从js中的透明像素获取rgb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!