Applying alpha paths to images in java

192 views Asked by At

I want to apply the alpha mask which is there in the image data. i have images of different formats namely tiffs,PSD PNGand jpeg.I am reading them as bufferedimage, and want to use the Twelvemonkeys lib to get the alpha paths configured in the images, and apply the transperency accordingly. But i can't find the relevant functions. Please help.

ImageInputStream stream = ImageIO.createImageInputStream(new File(c:/img.psd);
BufferedImage image = Paths.readClipped(stream);
image.getcoclormodel().hasAlpha(); 

for(i < image.getwidth()) {
   for(j < image.getHeight()) {
       pixels = image.getRGB(i, j, width, height, null, 0, width);
       Color col = new Color(pixels[pixelIndex]);
       int p = col.getAlpha() 
       image.setRGB(i, j, width, height, p, 0, width)
    }
}
1

There are 1 answers

0
Harald K On

Using the Paths.readClipped(...) method will read both the image data and the Photoshop clipping path resource, and apply the clipping path to the image. In other words, the resulting BufferedImage will contain transparency according to the path.

If you prefer to read the path and image separately, you could use the readPath(...) and applyClippingPath(...) methods of the Paths utility class:

try (ImageInputStream stream = ImageIO.createImageInputStream(new File("image_with_path.jpg")) {
    Shape clip = Paths.readPath(stream);
    stream.seek(0);
    BufferedImage image = ImageIO.read(stream);

    if (clip != null) {
        image = Paths.applyClippingPath(clip, image);
    }

    // Do something with the clipped image...
}

The above code basically does the same thing as readClipped(...) but allows you to inspect and modify each step.

PS: Note that the methods in Paths is for use only with images containing Photoshop Resource Blocks with ClippingPath resources (resource id 0x07d0). The alpha channel of the image will always be present. For PSD and TIFF files containing multiple alpha channels (aka "transparency masks"), there is currently no way to access the extra alpha channels.