0

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.

  • From a first glance at the code, I'd say that you have to set any rendering hints *before* you draw the image. But what you want to achieve is not entirely clear: What should happen to the colors that can *not* be represented? Should the "closest" color be chosen? This may be tricky... – Marco13 Mar 21 '14 at 18:23
  • Oh yes, the two 'RenderingHint' lines were originally in front of the 'drawImage' line. I corrected it. – Victor-Philipp Negoescu Mar 21 '14 at 18:25
  • @Victor-PhilippNegoescu You should post the update as an answer to your own question, and mark it as accepted. You'll gain bonus points AND the question will no longer appear in the "unanswered" queue. :-) PS: Wish I knew why your original code didn't work, but I have seen the same problem before and ended up with [a similar method](https://github.com/haraldk/TwelveMonkeys/blob/master/common/common-image/src/main/java/com/twelvemonkeys/image/CopyDither.java) as the one you describe. – Harald K Mar 22 '14 at 12:51
  • @haraldK Thank you, I had to wait at least 8 hours after posting the questions to answer it myself. – Victor-Philipp Negoescu Mar 24 '14 at 14:49

1 Answers1

1

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;
}