我看到一个关于将BufferedImage转换为像素/字节数组的线程。直接在图像上使用getRGB
可以正常工作,但不太理想,因为它太慢而无法收集所有像素。我尝试了另一种简单抓取像素数据的方法。
//convert canvas to bufferedimage
BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2 = img.createGraphics();
canvas.printAll(g2);
g2.dispose();
System.out.println(img.getRGB(0, 0)); //-16777216 works but not ideal
byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
for(byte b : pixels){
System.out.println(b); //all 0 doesnt work
}
但是,整个字节数组似乎是空的(用0填充)。
答案 0 :(得分:1)
我不知道代码中canvas
的含义,但这完全有效:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
public class Px {
public static void main(String[] args) {
new Px().go();
}
private void go() {
BufferedImage img = new BufferedImage(5, 5, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.red);
g2.fillRect(0, 0, 2, 2);
g2.dispose();
byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
for (byte b : pixels) {
System.out.print(b + ",");
}
}
}
结果如下:
0,0,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
颜色顺序为蓝绿红色。所以我的红色矩形在0,0,-1,0,0,-1等字节中显示为字节。我假设-1与255“相同”。
您可以探索自己的行canvas.printAll(
)。也许画布只包含黑色像素。