Question

I have a 256-color BufferedImage on which I want to draw another BufferedImage (> 256 colors). Java's default behaviour is to dither colors which cannot be representeed in the low-color model. I want to disable this (thus choosing the next best color available in the low-color model), so i tried to use RenderingHints to specify a new rendering behaviour but it does not work:

public BufferedImage filter(BufferedImage src) {
    BufferedImage convertedImage = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
    Graphics2D g2d = (Graphics2D) convertedImage.getGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
    g2d.drawImage(src, 0, 0, null);
    return convertedImage;
}

Ideas?

UPDATE:

I solved the problem by drawing the new image pixel-by-pixel which may not be very fast, but it works. See my answer for details.

Was it helpful?

Solution

I solved the problem by drawing the new image pixel-by-pixel which may not be very fast, but it works:

public BufferedImage filter(BufferedImage src) {
    BufferedImage convertedImage = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
    for (int x = 0; x < src.getWidth(); x++) {
        for (int y = 0; y < src.getHeight(); y++) {
            convertedImage.setRGB(x, y, src.getRGB(x, y));
        }
    }
    return convertedImage;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top