简体   繁体   中英

Java - Convert RAW to JPG/PNG

I have an image captured by a camera, in RAW BGRA format (byte array). How can I save it to disk, as a JPG/PNG file?

I've tried with ImageIO.write from Java API, but I got error IllegalArgumentException (image = null)

CODE:

try
{
    InputStream input = new ByteArrayInputStream(img);
    BufferedImage bImageFromConvert = ImageIO.read(input);

    String path = "D:/image.jpg";

    ImageIO.write(bImageFromConvert, "jpg", new File(path));
}
catch(Exception ex)
{
    System.out.println(ex.toString());
}

Note that "img" is the RAW byte array, and that is NOT null.

The problem is that ImageIO.read does not support raw RGB (or BGRA in your case) pixels. It expects a file format , like BMP, PNG or JPEG, etc.

In your code above, this causes bImageFromConvert to become null , and this is the reason for the error you see.

If you have a byte array in BGRA format, try this:

// You need to know width/height of the image
int width = ...;
int height = ...;

int samplesPerPixel = 4;
int[] bandOffsets = {2, 1, 0, 3}; // BGRA order

byte[] bgraPixelData = new byte[width * height * samplesPerPixel];

DataBuffer buffer = new DataBufferByte(bgraPixelData, bgraPixelData.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, samplesPerPixel * width, samplesPerPixel, bandOffsets, null);

ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);

BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

System.out.println("image: " + image); // Should print: image: BufferedImage@<hash>: type = 0 ...

ImageIO.write(image, "PNG", new File(path));

Note that JPEG is not a good format for storing images with alpha channel. While it is possible, most software will not display it properly. So I suggest using PNG instead.

Alternatively, you could remove the alpha channel, and use JPEG.

With Matlab you can convert all types of images with 2 lines of code:

img=imread('example.CR2');
imwrite(img,'example.JPG');

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