简体   繁体   中英

How to make bmp image from pixel byte array in java

I have a byte array containing pixel values from a.bmp file. It was generated by doing this:

BufferedImage readImage = ImageIO.read(new File(fileName));
byte imageData[] = ((DataBufferByte)readImage.getData().getDataBuffer()).getData();

Now I need to recreate the.bmp image. I tried to make a BufferedImage and set the pixels of the WritableRaster by calling the setPixels method. But there I have to provide an int[], float[] or double[] array. Maybe I need to convert the byte array into one of these. But I don't know how to do that. I also tried the setDataElements method. But I am not sure how to use this method either.

Can anyone explain how to create a bmp image from a byte array?

Edit: @Perception

This is what I have done so far:

private byte[] getPixelArrayToBmpByteArray(byte[] pixelData, int width, int height, int depth) throws Exception{ int[] pixels = byteToInt(pixelData); BufferedImage image = null; if(depth == 8) { image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); } else if(depth == 24){ image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } WritableRaster raster = (WritableRaster) image.getData(); raster.setPixels(0, 0, width, height, pixels); image.setData(raster); return getBufferedImageToBmpByteArray(image); } private byte[] getBufferedImageToBmpByteArray(BufferedImage image) { byte[] imageData = null; try { ByteArrayOutputStream bas = new ByteArrayOutputStream(); ImageIO.write(image, "bmp", bas); imageData = bas.toByteArray(); bas.close(); } catch (Exception e) { e.printStackTrace(); } return imageData; } private int[] byteToInt(byte[] data) { int[] ints = new int[data.length]; for (int i = 0; i

You need to pack three bytes into each integer you make. Depending on the format of the buffered image, this will be 0xRRGGBB.

byteToInt will have to consume three bytes like this:

private int[] byteToInt(byte[] data) {
    int[] ints = new int[data.length / 3];

    int byteIdx = 0;
    for (int pixel = 0; pixel < ints.length) {
        int rByte = (int) pixels[byteIdx++] & 0xFF;
        int gByte = (int) pixels[byteIdx++] & 0xFF;
        int bByte = (int) pixels[byteIdx++] & 0xFF;
        int rgb = (rByte << 16) | (gByte << 8) | bByte
        ints[pixel] = rgb;
    }
}

You can also use ByteBuffer.wrap(arr, offset, length) .toInt()

Having just a byte array is not enough. You also need to construct a header (if you are reading from a raw format, such as inside a DICOM file).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM