Question

I need to apply a tint to a grayscale BufferedImage with transparency without influencing the transparency itself, this is the method i use, but when i try to draw it on top of another image inside a canvas, the transparency of the original image is gone, leaving a square of the raw selected color...

private BufferedImage colorize(BufferedImage original,Color tint) { //TODO fix!!!

BufferedImage img = new BufferedImage(original.getWidth(), original.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);

int redVal=tint.getRed();
int greenVal=tint.getGreen();
int blueVal=tint.getBlue();

for (int x=0;x<original.getWidth();x++) for (int y=0;y<original.getHeight();y++) {
    Color pixelVal=new Color(original.getRGB(x, y));
    int grayValue=pixelVal.getRed();  //Any basic color works the same
    int alpha=pixelVal.getAlpha();
    int newRed= (redVal*(grayValue))/255;
    int newGreen= (greenVal*grayValue)/255;
    int newBlue= (blueVal*grayValue)/255;
    img.setRGB(x, y, new Color(newRed,newGreen,newBlue,alpha).getRGB());
}
return img;}

Any hint?

Was it helpful?

Solution

Use the Color constuctor that takes two arguments:

 Color pixelVal = new Color(original.getRGB(x, y), true);

This constructor creates a Color with an ARGB color, if the hasAlpha parameter is true.

The single argument constructor Color(int) does not take transparency into account. From the JavaDoc:

Creates an opaque sRGB color with the specified combined RGB value [...] Alpha is defaulted to 255.

Apart from that, your code should probably work. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top