我有一个字节数组,大小为640 * 480 * 3,字节顺序为r,g,b。我正在尝试将其转换为Image。以下代码不起作用:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
with excepton
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
我也试过这段代码:
ImageIcon imageIcon = new ImageIcon(data);
Image img = imageIcon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_3BYTE_BGR); //Exception
但未成功:
Exception in thread "main" java.lang.IllegalArgumentException: Width (-1) and height (-1) must be > 0
如何从此阵列接收图像?
答案 0 :(得分:2)
普通字节数组不是通常识别的图像格式。您必须自己编写转换代码。幸运的是,它不是很难做到:
int w = 640;
int h = 480;
BufferedImage i = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for (int y=0; y<h; ++y) {
for (int x=0; x<w; ++x) {
// calculate index of pixel
// depends on exact organization of image
// sample assumes linear storage with r, g, b pixel order
int index = (y * w * 3) + (x * 3);
// combine to RGB format
int rgb = ((data[index++] & 0xFF) << 16) |
((data[index++] & 0xFF) << 8) |
((data[index++] & 0xFF) ) |
0xFF000000;
i.setRGB(x, y, rgb);
}
}
像素索引的确切公式取决于您如何组织数组中的数据 - 您没有真正精确指定。原则总是相同的,将R,G,B值组合成RGB(精确到ARGB)值,并使用setRGB()方法将其放入BufferedImage。