Site iconJava PDF Blog

How to Convert a Java BufferedImage between Colorspaces

Java icon

The Java BufferedImage class provides a very powerful ‘abstraction’ of images in Java. It lets you create a huge array of image types which can all be seamlessly accessed. One of its key features is that you can decide what type of image you have – black and white, grayscale or full ARGB.

When we create an image from a PDF in JPedal, we use an ARGB BufferedImage because it is the only mode which support the color range and transparency which can be found in many PDFs.

Sometimes, you want to convert a BufferedImage from one type to another, and Java makes this very easy. We have a method in our ColorSpaceConvertor class convertColorspace(image, type) which does the conversion but the code is very simple and reproduced below. The Type is a constant from BufferedImage so making a page GRAY would need

image=ColorSpaceConvertor.convertColorspace(image, BufferedImage.TYPE_BYTE_GRAY);

/**
 * convert a BufferedImage to RGB colourspace
 */final public static BufferedImage convertColorspace(
BufferedImage image,
int newType) {

try {
BufferedImage raw_image = image;
image =
new BufferedImage(
raw_image.getWidth(),
raw_image.getHeight(),
newType);
ColorConvertOp xformOp = new ColorConvertOp(null);
xformOp.filter(raw_image, image);
} catch (Exception e) {
LogWriter.writeLog("Exception " + e + " converting image");

}

return image;
}

One issue that can arise is that detail can be lost so an alternative method is to create an image in the format you need and then draw the original image onto it. Here is how you can do this

BufferedImage image_to_save2=new BufferedImage(image_to_save.getWidth(),image_to_save.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
image_to_save2.getGraphics().drawImage(image_to_save,0,0,null);
image_to_save = image_to_save2;