1
\$\begingroup\$

I wanted to know how to tint a (Buffered)Image in Java

With "tinting" I mean that black pixels stay black and grey/white pixels become the colour I want. Of Course not all pictures are grayscale

I tried to paint the Image with 50% Alpha colour, but the results are not satisfying.

Does someone know a Solution for this? Here you can see what I want:

enter image description here The bottom right picture is, What I have with 50% alpha colour. the Top Right is, what I want.

A somehow linked question to this: Is painting the image via setRGB() for each pixel faster than BufferedImage.getGraphics() and paint on the Graphics Object?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ If you have the color data for each pixel in float format, in the range of 0..1, you should be able to simply multiply each pixel in the image with the color, you want to tint it with. \$\endgroup\$ Sep 27, 2015 at 8:41

1 Answer 1

0
\$\begingroup\$

Thanks to the comment above, I found the answer

protected BufferedImage tint(float r, float g, float b, float a,
                            BufferedImage sprite)
  {
    BufferedImage tintedSprite = new BufferedImage(sprite.getWidth(), sprite.
            getHeight(), BufferedImage.TRANSLUCENT);
    Graphics2D graphics = tintedSprite.createGraphics();
    graphics.drawImage(sprite, 0, 0, null);
    graphics.dispose();

    for (int i = 0; i < tintedSprite.getWidth(); i++)
    {
      for (int j = 0; j < tintedSprite.getHeight(); j++)
      {
        int ax = tintedSprite.getColorModel().getAlpha(tintedSprite.getRaster().
                getDataElements(i, j, null));
        int rx = tintedSprite.getColorModel().getRed(tintedSprite.getRaster().
                getDataElements(i, j, null));
        int gx = tintedSprite.getColorModel().getGreen(tintedSprite.getRaster().
                getDataElements(i, j, null));
        int bx = tintedSprite.getColorModel().getBlue(tintedSprite.getRaster().
                getDataElements(i, j, null));
        rx *= r;
        gx *= g;
        bx *= b;
        ax *= a;
        tintedSprite.setRGB(i, j, (ax << 24) | (rx << 16) | (gx << 8) | (bx));
      }
    }
    return tintedSprite;
  }

where r, g, b and a are floats between 0 and 1

\$\endgroup\$
1
  • \$\begingroup\$ This is usually called multiplicative image compositing. \$\endgroup\$
    – Philipp
    Feb 26, 2016 at 11:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .