从字节数组转换和显示图像 [英] Convert and display image from byte array
问题描述
我正在制作一个程序,它从服务器获取有关字节数组中图像的数据.我正在将此数据转换为 24 位 BMP 格式(无论是 jpeg、png、bmp 还是 8-24-32bpp).首先,我将它保存到我的 HD,然后我将它加载到 JLabel 的图标中.工作完美,但在某些情况下我会遇到以下异常:
I'm making a program, which gets data about an image in byte array from a server. I'm converting this data into 24bit BMP format (whether its jpeg, png, bmp or 8-24-32bpp). First, I'm saving it to my HD, and then I'm loading it into a JLabel's Icon. Works perfectly, though there are some cases in which I get the following exception:
java.io.EOFException at
javax.imageio.stream.ImageInputStreamImpl.readFully(ImageInputStreamImpl.java:353) at
com.sun.imageio.plugins.bmp.BMPImageReader.read24Bit(BMPImageReader.java:1188) at
com.sun.imageio.plugins.bmp.BMPImageReader.read(BMPImageReader.java:843) at
javax.imageio.ImageIO.read(ImageIO.java:1448) at
javax.imageio.ImageIO.read(ImageIO.java:1308)
对于这一行(第二条)
File imgFile = new File("d:/image.bmp");
BufferedImage image = ImageIO.read(imgFile);
在这些情况下:
- 图像无法加载到 JLabel 中,但可以在我的 HD 中找到
- 转换不正确,因为有些错误"
- 图片就像你在word文档中使用斜体
首先,我认为可能 bpp 是问题所在,然后我认为可能图片太大,但我有两种建议都有效的情况和不适用的情况.我有点卡在这里,很高兴有想法.
First, i thought maybe the bpp is the problem, then i thought that maybe the pictures are too large, but i have cases it works and cases it doesn't for both suggestions. I'm a little stuck here, and would be glad for ideas.
推荐答案
- 图片就像..当你在word文档中使用斜体
我想我现在终于明白这个项目符号是什么意思了..;-)
Think I finally got what this bullet item meant now.. ;-)
推测性的答案,但这里是:
Speculative answer, but here goes:
如果您编写的图像看起来倾斜",这可能是由于 BMP 格式指定的每列缺少填充(或 BMP 标题中的宽度字段不正确).然后我假设,您获得 EOF 例外的图像的宽度不是 4 的倍数.
If the image you write looks "skewed", it's probably due to missing padding for each column as the BMP format specifies (or incorrect width field in the BMP header). I assume then, that the images you get EOF exceptions for, is where the width is not a multiple of 4.
尝试使用 ImageIO 编写 BMP,看看是否有帮助:
Try to write the BMPs using ImageIO to see if that helps:
private static BufferedImage createRGBImage(byte[] bytes, int width, int height) {
DataBufferByte buffer = new DataBufferByte(bytes, bytes.length);
ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[]{8, 8, 8}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
return new BufferedImage(cm, Raster.createInterleavedRaster(buffer, width, height, width * 3, 3, new int[]{0, 1, 2}, null), false, null);
}
...
byte[] bytes = ...; // Your image bytes
OutputStream stream = ...; // Your output
BufferedImage image = createRGBImage(bytes, width, height);
try {
ImageIO.write(image, "BMP", stream);
}
finally {
stream.close();
}
这篇关于从字节数组转换和显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!