Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change alpha of image in java for method drawImage()

I'm trying to change the transparency of an image over time, and I'm doing this with the method drawImage() from java.awt.Graphics. I know there's a lot of different answers online about how to do this, but I can't find a one that is simple enough for me to understand and implement.

Let's just say I have a BufferedImage image, and I want to draw this image with a 50% opacity. How would I initialize image and what would I do to adjust the alpha level of the image when I draw it. It would be great if I could use the method drawImage() and do something with that to change the transparency of the image, but it's probably not that simple.

like image 462
applemavs Avatar asked Dec 02 '25 06:12

applemavs


2 Answers

Never tried it, but I think the basic code would be:

AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
g2d.setComposite(ac);
g2d.drawImage(...);
like image 76
camickr Avatar answered Dec 03 '25 22:12

camickr


Using image filter.

float[] scales = { 1f, 1f, 1f, 0.1f };
float[] offsets = new float[4];
RescaleOp rop = new RescaleOp(scales, offsets, null);
g2d.drawImage(buffimg, rop, 0, 0);

4th element in scales array is transparency, this value goes between 0 - 1

Answer by camickr will make the entire component apply the alpha including all inner components. But that will be much faster.

Warning: Use Image Filters with Care

ref: http://www.informit.com/articles/article.aspx?p=1013851&seqNum=2

like image 37
Stalin Gino Avatar answered Dec 03 '25 20:12

Stalin Gino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!