Changing Image Opacity

animation, image, java, opacity, resize

Solution

first make sure the type you're passing into to method contains an alpha channel, like

BufferedImage.TYPE_INT_ARGB

and then just before you paint the new image, call the Graphics2D method setComposite like so:

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

that will set the drawing opacity to 50%.

Problem

In a project, I want to simultaneously resize and change the opacity of an image. So far I think I've got the resizing down. I use a method defined like so to accomplish the resizing: ``` 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. What I can't find a solution to is changing the opacity. That's what I'm wondering how to do (if it's possible at all). Thanks in advance. UPDATE: I tried this code to display a picture of a circle with transparent insides and outsides (see below image) growing and becoming less and less opaque, but it didn't work. I'm not sure what's wrong. All the code is in a class called 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 like this: ``` 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); } ```

Original source