如何使用透明填充缩放Graphics2D图像 [英] How to scale a Graphics2D image with transparent padding
问题描述
我正在尝试编写一个小方法,它采用 BufferedImage
图像和新的宽度和高度,并通过添加透明边框来缩放保持纵横比的图像左/右或上/下取决于图像。缩放工作正常,但对于我的生活,我无法使边框透明。
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.
到目前为止,我有在pastebin.com上发布了以下代码,它可以很好地扩展。
So far I have the following code posted on pastebin.com which does the scaling well.
我读了很多手册和其他SO问题无济于事。我尝试了很多填充,复合类型,图像类型等的排列。有时我得到一个蓝色背景,有时是白色但它似乎永远不会透明。
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;
知道我需要做什么Graphics2D才能拥有 Color.WHITE
背景是透明的和在旧的上面绘制旧图像?感谢您的帮助。
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.
修改:
原来这个问题我当时正试图用JPEG图像生成透明色。 JPEG不支持透明度。 Duh。
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.
推荐答案
我刚试了一下它的确有效。
I've just tried it out and it works.
只需将 Color.WHITE
替换为新颜色(0,0,0,0)
和 img.getType()
with BufferedImage.TYPE_INT_ARGB
。
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)
newImage.png:(300x100)
这篇关于如何使用透明填充缩放Graphics2D图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!