Graphics2D 图片合成、图片处理 应注意的细节和踩过的坑

Graphics2D 2d https://docs.oracle.com/javase/8/docs/api/java/awt/Graphics2D.html

图片处理

首先画布肯定是需要的,可以新建一个空白画布,也可以以图片做画布。

BufferedImage  bi = new BufferedImage(width,height,type);

2d = bi.createGraphics();

如果需要生成RGB格式,需要做如下配置

bi = 2d.getDeviceConfiguration().createCompatibleImage(width,height,Transparency.TRANSLUCENT);

注:参数width 和 height 要和是前面画布的对应。

Transparency透明度设置

画图 g.drawImage(

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Graphics2DJava 2D API 中的一个类,用于在 Java 用程序中绘制 2D 图形。Graphics2D 类提供了一些方法来处理不同类型的 2D 图形,例如线条、矩形、椭圆、弧形、多边形等。 要使用 Graphics2D 类来绘制图片,可以使用以下步骤: 1. 创建一个 BufferedImage 对象,该对象可以用来存储要绘制的图片。 ``` BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); ``` 其中,widthheight 分别是图片的宽度和高度,BufferedImage.TYPE_INT_ARGB 是指图像类型为 32 位 ARGB。 2. 获取 Graphics2D 对象,该对象可以用来绘制图形。 ``` Graphics2D g2d = image.createGraphics(); ``` 3. 使用 Graphics2D 对象的 drawImage() 方法将所需的图像绘制到 BufferedImage 对象上。 ``` g2d.drawImage(img, x, y, null); ``` 其中,img 是要绘制的图像,x 和 y 分别是图像的起始位置的 x 和 y 坐标。 4. 最后,关闭 Graphics2D 对象。 ``` g2d.dispose(); ``` 完整的代码示例: ```java import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageDraw { public static void main(String[] args) { int width = 500; int height = 500; // 创建 BufferedImage 对象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // 获取 Graphics2D 对象 Graphics2D g2d = image.createGraphics(); // 绘制图像 try { BufferedImage img = ImageIO.read(new File("image.jpg")); int x = (width - img.getWidth()) / 2; int y = (height - img.getHeight()) / 2; g2d.drawImage(img, x, y, null); } catch (Exception e) { e.printStackTrace(); } // 关闭 Graphics2D 对象 g2d.dispose(); // 保存图像到文件 try { ImageIO.write(image, "png", new File("output.png")); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码将会创建一个 500x500 像素的 BufferedImage 对象,并将一张名为 "image.jpg" 的图像绘制在中心位置,最后将结果保存为名为 "output.png" 的 PNG 图像文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值