如何从java中的像素字节数组制作bmp图像 [英] How to make bmp image from pixel byte array in java
问题描述
我有一个包含来自 .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
这是我目前所做的:
推荐答案
您需要将三个字节打包到您创建的每个整数中.根据缓冲图像的格式,这将是 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;
}
}
您也可以使用 ByteBuffer.wrap(arr, offset, length).toInt()
You can also use ByteBuffer.wrap(arr, offset, length).toInt()
这篇关于如何从java中的像素字节数组制作bmp图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!