java将字符串保存为图片
因为最近接触到的需求是要将指定的字符串内容保存为图片,我知道肯定要用awt相关的东西,但是以前没有接触过awt,所以只能去网上学习相关的东西和找有关的资料,好在最后可以解决,直接上代码:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;/*** @Description 通用工具类* @ClassName CommonUtil* @Author yanchengzhi* @date 2021.06.22 21:19*/
public final class CommonUtil {/** @description: 将字符串转换为BufferedImage对象* @param: [strs]* @return: java.awt.image.BufferedImage* @author: yanchengzhi* @date: 2021/6/22 21:20*/public static BufferedImage createImage(String[] strs) {// 设置背景宽高int width = 600, height = 400;BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取图形上下文对象Graphics graphics = image.getGraphics();// 填充graphics.fillRect(0, 0, width, height);// 设定字体大小及样式graphics.setFont(new Font("宋体", Font.BOLD,34));// 字体颜色graphics.setColor(Color.BLUE);for (int i = 0; i < strs.length; i++) {// 描绘字符串graphics.drawString(strs[i], 150, 70+ (i + 1) * 50);}graphics.dispose();return image;}
}
测试:
public class Test {public static void main(String[] args) throws IOException {String strs[] = new String[4];strs[0] = "前尘往事断肠诗,";strs[1] = "侬为君痴君不知。";strs[2] = "莫道世间真意少,";strs[3] = "自古人间多情痴。";// 获取BufferedImage对象BufferedImage image = CommonUtil.createImage(strs);File file = new File("C:/Users/17605/Desktop");String fileName = "无题.jpg";File jpgFile = new File(file,fileName);if(!jpgFile.exists()) {jpgFile.createNewFile();}// 创建图片输出流对象,基于文件对象ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(jpgFile);// 写入ImageIO.write(image,"jpg",imageOutputStream);// 关闭流imageOutputStream.close();System.out.println("图片写入完成,请查看!");}
}
生成了一个无题.jpg
的图片,查看图片: