https://www.cnblogs.com/donghb/p/7637990.html

BufferedImage

1
2
BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
image = image.getSubimage(50, 50, 20, 20);

ImageIO

1
ImageIO.write(image, "jpg", new File("C:\\Users\\lenovo\\Desktop\\image.jpg"));

GraphicsGraphics2D

Graphics类提供基本绘图方法,Graphics2D类提供更强大的绘图能力。

Graphics类提供基本的几何图形绘制方法,主要有:画线段、画矩形、画圆、画带颜色的图形、画椭圆、画圆弧、画多边形等。

Graphics

1
2
3
4
5
6
7
8
9
10
11
public class TransparentImage {
private static int IMG_WIDTH = 100;
private static int IMG_HEIGHT = 100;

public static void main(String[] args) throws IOException {
BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.drawLine(0, 0, 100, 100);
ImageIO.write(image, "jpg", new File("C:\\Users\\lenovo\\Desktop\\image.jpg")); // 向页面输出图像
}
}
  • 画一条线
1
g.drawLine(0, 0, 100, 100);
  • 画矩形
1
2
3
g.drawRect(0,0,50,50);
g.setColor(Color.lightGray);
g.fillRect(50,50,20,20);
  • 画圆
1
2
3
g.drawRoundRect(5, 5, 30, 30, 30, 30);
g.setColor(Color.lightGray);
g.fillRoundRect(30, 30, 30, 30, 30, 30);

Graphics2D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class RenderingHintCase {
public static void main(String[] args) throws IOException {
BufferedImage image = new BufferedImage(260, 80, BufferedImage.TYPE_INT_BGR);
//获取Graphics2D对象
Graphics2D graphics = image.createGraphics();
//开启文字抗锯齿
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//设置字体
Font font = new Font("Algerian", Font.ITALIC, 40);
graphics.setFont(font);
//向画板上写字
graphics.drawString("This is test!", 10, 60);
graphics.dispose();

ImageIO.write(image, "jpg", new File("C:\\Users\\lenovo\\Desktop\\demo.jpg"));
}
}