如何从java中的像素字节数组制作bmp图像 [英] How to make bmp image from pixel byte array in java

查看:162
本文介绍了如何从java中的像素字节数组制作bmp图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,其中包含来自.bmp文件的像素值.它是通过执行以下操作生成的:

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

现在,我需要重新创建.bmp图像.我试图制作一个BufferedImage并通过调用setPixels方法设置WritableRaster的像素.但是我必须提供一个int [],float []或double []数组.也许我需要将字节数组转换为其中之一.但是我不知道该怎么做.我还尝试了setDataElements方法.但是我也不知道如何使用这种方法.

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.

任何人都可以解释如何从字节数组创建bmp图像吗?

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

@Perception

@Perception

这是我到目前为止所做的:

This is what I have done so far:

问题是,这仅适用于灰色图像,但是对于彩色图像,颜色是不正确的.我认为这与byteToInt方法有关.如果有人知道如何改进它或有一个新的更简单的解决方案,我们将为您提供帮助.:)

The thing is this works just fine for gray images, but for colored images the color is not correct. I think this is something to do with the byteToInt method.. If someone knows how to improve it or have got a new and easier solution, ur help will be appreciated.. :)

推荐答案

您需要将三个字节打包成每个整数.根据缓冲图像的格式,该值为0xRRGGBB.

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

byteToInt必须像这样消耗三个字节:

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

这篇关于如何从java中的像素字节数组制作bmp图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆