Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale a Graphics2D image with transparent padding

I'm trying to write a small method which takes a BufferedImage image and a new width and height and scales the image keeping the aspect ratio by adding transparent border to the left/right or top/bottom depending on the image. The scaling works fine but for the life of me I can't get the border to be transparent.

So far I have the following code posted on pastebin.com which does the scaling well.

I've read a lot of manuals and other SO questions to no avail. I've tried numerous permutations of fills, composite types, image types, etc.. Sometimes I get a blue background, sometimes white but it never seems to be transparent.

BufferedImage newImg = new BufferedImage(newWidth, newHeight, img.getType());
Graphics2D g = newImg.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, newWidth, newHeight);
g.drawImage(img, x, y, x + scaledWidth, y + scaledHeight, 0, 0,
    currentWidth, currentHeight, Color.WHITE, null);
g.dispose();
return newImg;

Any idea what Graphics2D call I need to make to have the Color.WHITE background be transparent and draw the old image over the new? Thanks for any help.

Edit:

It turned out that the problem I was having was that I was trying to generate a transparent color with a JPEG image. JPEGs do not support transparency. Duh.

like image 865
Gray Avatar asked Jan 14 '23 02:01

Gray


1 Answers

I've just tried it out and it works.

Just replace Color.WHITE with new Color(0, 0, 0, 0), and img.getType() with BufferedImage.TYPE_INT_ARGB.


BufferedImage img = ImageIO.read(new File("image.png"));
BufferedImage outImage = scaleWithPadding(img, 300, 100);
ImageIO.write(outImage, "png", new File("newImage.png"));

image.png: (204x53)

enter image description here

newImage.png: (300x100)

enter image description here

like image 176
Eng.Fouad Avatar answered Jan 19 '23 10:01

Eng.Fouad