Convert and display image from byte array

自作多情 提交于 2019-11-29 10:38:01
  • the picture is like .. when You use italics in a word document

Think I finally got what this bullet item meant now.. ;-)

Speculative answer, but here goes:

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.

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();
}

Call it by class name, liek ClassName.byteArrayToImage(byte):

public static BufferedImage  byteArrayToImage(byte[] bytes){  
        BufferedImage bufferedImage=null;
        try {
            InputStream inputStream = new ByteArrayInputStream(bytes);
            bufferedImage = ImageIO.read(inputStream);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        return bufferedImage;
}
Mohsin Shaikh

You can use this code to convert the output image to a byte Array

   Blob b = rs.getBlob(2);
   byte barr[] = new byte[(int)b.length()]; //create empty array
   barr = b.getBytes(1,(int)b.length());

   FileOutputStream fout = new FileOutputStream("D:\\sonoo.jpg");
   fout.write(barr);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!