Java Bitmap RLE8 format

1k views Asked by At

Does Java ImageIO (or any other image handlers) support BI_RLE8 image format? The only thing I have managed to find is BMPImageWriteParam but I have no idea whatsoever how to use that. Any help would be wonderful.

2

There are 2 answers

0
Harald K On BEST ANSWER

See this example for how to write using ImageWriter and using ImageWriteParam (use an instance of BMPImageWriteParam in your case). Scroll a bit down to find the write example.

Instead of the line:

ImageWriteParam param = writer.getDefaultWriteParam();

You should insert something like:

BMPImageWriteParam param = new BMPImageWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("BI_RLE8");

You can safely pass null for thumbnails and metadata (... in the example).

0
icza On

If you want to save an image using custom parameters, you have to use an ImageWriter to which you can pass custom parameters to write the output file.

You can get the params from an ImageWriter using its getDefaultWriteParam() method where you can set the compression type. You don't even have to cast it to BMPImageWriteParam because setting the compression type is available via the ImageWriter super interface.

Note that in order to use a custom compression type, you have to set the compression mode to ImageWriteParam.MODE_EXPLICIT.

Here is the complete code:

BufferedImage bi = new BufferedImage(200, 100, BufferedImage.TYPE_BYTE_INDEXED);

ImageWriter writer  = ImageIO.getImageWritersByFormatName("bmp").next();
ImageWriteParam param = writer.getDefaultWriteParam();

param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("BI_RLE8");

writer.setOutput(new FileImageOutputStream(new File("test.bmp")));
writer.write(null, new IIOImage(bi, null, null), param);
writer.dispose();        

Note that BI_RLE8 compression is not available for all types of BufferedImages.
For exmaple BI_RLE8 compression is supported for BufferedImage.TYPE_BYTE_INDEXED and BufferedImage.TYPE_BYTE_GRAY but it is not supported for BufferedImage.TYPE_3BYTE_BGR in which case an IOException will be thrown by the ImageWriter.write() method (which is actually BMPImageWriter.write()).