[英]Convert byte array to Image
我有一個字節數組,其大小為640 * 480 * 3,其字節順序為r,g,b。 我正在嘗試將其轉換為Image。 以下代碼不起作用:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(data));
與除了
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
如何從此陣列接收圖像?
普通字節數組不是通常識別的圖像格式。 您必須自己編寫轉換代碼。 幸運的是,它不是很難做到:
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中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.