private BufferedImage convert(BufferedImage image, int imageType) { if (image.getType() == imageType) { return image; } int w = image.getWidth(); int h = image.getHeight(); BufferedImage newImg = new BufferedImage(w, h, imageType); ColorSpace srcSpace = image.getColorModel().getColorSpace(); ColorSpace newSpace = newImg.getColorModel().getColorSpace(); ColorConvertOp convert = new ColorConvertOp(srcSpace, newSpace, null); convert.filter(image, newImg); return newImg; }
/** * Simple method to use if one wants to change the current color scheme to e.g grayscale, * black/white and so on * * @param source source image object * @param colorSpaceType color space type. see java.awt.color.ColorSpace.<TYPES> * @param <T> type * @return BufferedImage * @throws IOException _ * @throws NullPointerException _ */ public static <T> BufferedImage convertColorScheme(final T source, final Integer colorSpaceType) throws IOException, NullPointerException { if (verifyNotNull(source, colorSpaceType)) { BufferedImage sourceImage; sourceImage = convertToBufferedImage(source); BufferedImage target = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType()); if (verifyNotNull(sourceImage)) { ColorSpace colorSpace = ColorSpace.getInstance(colorSpaceType); ColorConvertOp converter = new ColorConvertOp(colorSpace, null); target = converter.filter(sourceImage, target); if (verifyNotNull(target)) { return target; } throw new NullPointerException("Unable to create target image. Result was null"); } } throw new NullPointerException(E_OBJECT_WAS_NULL); }