开发环境:
IDEA,JDK1.8,SpringBoot
具体源码:
package com.xxx.xxxx;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @author kyrielx
* @since 2023/3/21
*/
@SpringBootTest
public class Graphics2DTest {
/**
* 在一张照片上绘制文本信息,然后生成一张新的照片
*/
@Test
public void test1() throws IOException {
// 1. 读取本地照片
File file = new File("C:\\Users\\11988\\Pictures\\tdpic.png");
Image srcImg = ImageIO.read(file);
int srcImgWidth = srcImg.getWidth(null);
int srcImgHeight = srcImg.getHeight(null);
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
// 2. 绘制
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
g.setColor(Color.RED);
Font font = new Font("楷体", Font.BOLD, 32);
g.setFont(font);
int x = srcImgWidth/2 - 32;
int y = srcImgHeight/2;
g.drawString("小明", x, y);
g.dispose();
// 3. 生成新照片
ImageIO.write(bufImg, "png", new File("C:\\Users\\11988\\Pictures\\", "tdpic-new.png"));
}
}
运行完成,生成新照片:
参考链接
https://www.manongdao.com/article-2044004.html