Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
1  
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. – user000user Sep 27 '15 at 8:41
    
Thank you that worked! – Raildex Sep 27 '15 at 16:20
up vote 0 down vote accepted

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

share|improve this answer
    
This is usually called multiplicative image compositing. – Philipp Feb 26 '16 at 11:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.