bufferedImage 图片背景透明
时间: 2023-09-11 13:12:11 浏览: 104
要将 BufferedImage 图片的背景设置为透明,可以通过以下几个步骤实现:
1. 创建一个带有透明通道的 BufferedImage 对象,可以使用 BufferedImage 类的静态方法 createCompatibleImage() 来创建。
```java
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
```
2. 获取到该 BufferedImage 对象的 Graphics2D 对象,并将其设置为透明背景。
```java
Graphics2D g2d = image.createGraphics();
g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.Src);
```
3. 在该 Graphics2D 对象上绘制你需要的图形或图片,其背景将会自动为透明。
```java
g2d.drawImage(sourceImage, 0, 0, null);
```
完整代码示例:
```java
BufferedImage sourceImage = ImageIO.read(new File("source_image.png"));
int width = sourceImage.getWidth();
int height = sourceImage.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setComposite(AlphaComposite.Clear);
g2d.fillRect(0, 0, width, height);
g2d.setComposite(AlphaComposite.Src);
g2d.drawImage(sourceImage, 0, 0, null);
g2d.dispose();
ImageIO.write(image, "png", new File("transparent_image.png"));
```
阅读全文