1

I am trying to write a code where I get a png/jpeg image. If it is a png image, I want to check if it's background is 100% transparent. If yes, I want to add white background using image magick.

Currently I use image magick's "identify -format %A new.png" which returns true or false based on transparency.

However, is there any way to find out 100 percent background transparency using image magick or java code?

Mayank_Thapliyal
  • 351
  • 2
  • 7
  • 16

1 Answers1

1

You could iterate over each pixel in the image and check whether the most significant byte (which is the alpha channel) is zero (as explained here). Do it somehow like this:

public static boolean isFullyAlpha(File f) throws IOException {
    BufferedImage img = ImageIO.read(f);
    for(int y = 0; y < img.getHeight(); y++) {
        for(int x = 0; x < img.getWidth(); x++) {
            if(((img.getRGB(x, y) >> 24) & 0xFF) != 0) {
                return false;
            }
        }
    }
    return true;
}
Community
  • 1
  • 1
Prior99
  • 619
  • 5
  • 13
  • I understand your solution, but the code written here returns false for any image. Can you please provide the correct code? – Mayank_Thapliyal May 19 '14 at 10:51
  • I checked the alpha values and for the tranparent image,it was 6 and for the non transparent ones it was 255. SO the method requires little tweaking, but its working fine. Maybe a check if alpha is 255 then return true, else false – Mayank_Thapliyal May 19 '14 at 10:57
  • I checked it using `BufferedImage img = ImageIO.read(new URL("http://www.cityrider.com/fixed/43aspect.png"));` in the second line and it works just fine, returning true. Maybe your image isn't really fully alpha? Then you might want to check if it less than a threshold. (So don't compare for != 0 in the if-statement but check for <= 10 or some similiar value) – Prior99 May 19 '14 at 11:00
  • 1
    Checking for the alpha to be 255 and then to return true is generally a bad idea for two reasons: First: Even on fully transparent images you will have to iterate over the whole image before being able to exit the loops which will result in always being the worst-case-scenario, second, which is much more significant: If you are testing an image having pixel which are not fully alpha, it will also fail. I think the answer supplies everything you need to form a good approach to your specific problem. Just tweak it as needed. – Prior99 May 19 '14 at 11:03
  • Absolutely right. I would vote you up but I dont have required reputation level . :) Thanks for the help nonetheless – Mayank_Thapliyal May 19 '14 at 11:06
  • Bear in mind that `ImageIO.read()` (at least the default reader that comes with Oracle JRE 7) does not recognize transparency for true-colour (or gray) images (variant 2b : http://stackoverflow.com/questions/13569887/libpng-palette-png-with-alpha-or-not/13570973#13570973 ) It's not very frequent, though. – leonbloy May 19 '14 at 14:22