Convert and display image from byte array

后端 未结 3 457
再見小時候
再見小時候 2020-12-19 03:00

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)

相关标签:
3条回答
  • 2020-12-19 03:10
    • 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();
    }
    
    0 讨论(0)
  • 2020-12-19 03:21

    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);
    
    0 讨论(0)
  • 2020-12-19 03:24

    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;
    }
    
    0 讨论(0)
提交回复
热议问题