Change the opacity of the image

In the project, I want to simultaneously resize and change the opacity of the image. So far, I think I have a resize. I use a method defined to resize:

public BufferedImage resizeImage(BufferedImage originalImage, int type){ initialWidth += 10; initialHeight += 10; BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null); g.dispose(); return resizedImage; } 

I got this code from here. The fact that I cannot find a solution is a change in opacity. This is what I wonder how to do it (if at all possible). Thanks in advance.

UPDATE

I tried this code to display a circle image with transparent internal and external (see image below), which grows and becomes less and less opaque, but it did not work. I'm not sure what happened. All code is in class Animation

 public Animation() throws IOException{ image = ImageIO.read(new File("circleAnimation.png")); initialWidth = 50; initialHeight = 50; opacity = 1; } public BufferedImage animateCircle(BufferedImage originalImage, int type){ //The opacity exponentially decreases opacity *= 0.8; initialWidth += 10; initialHeight += 10; BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type); Graphics2D g = resizedImage.createGraphics(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null); g.dispose(); return resizedImage; } 

I call it this way:

 Animation animate = new Animation(); int type = animate.image.getType() == 0? BufferedImage.TYPE_INT_ARGB : animate.image.getType(); BufferedImage newImage; while(animate.opacity > 0){ newImage = animate.animateCircle(animate.image, type); g.drawImage(newImage, 400, 350, this); } 
+8
java opacity image resize animation
source share
1 answer

first make sure that the type you pass to the method contains an alpha channel, e.g.

 BufferedImage.TYPE_INT_ARGB 

and then before you draw a new image, call the Graphics2D setComposite method as follows:

 float opacity = 0.5f; g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); 

which will set the transparency of the picture to 50%.

+19
source share

All Articles