package com.ruoyi.tupian.javaToPage;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.;
import java.nio.file.Paths;
import java.util.Base64;
public class page {
public static void main(String[] args) throws Exception {
String rootPath = “E:\”;
String str = “苞米豆”;
createImage(str, new Font(“宋体”, Font.PLAIN, 100), Paths.get(rootPath, “医生名称.png”).toFile());
//将本地图片转成base64保存到数据库
String pageBase64 = ImgToBase64(“E:\医生名称.png”);
System.out.println(“base64编码:”+pageBase64);
Base64ToImg(pageBase64,“E:\医生名称1.png”);
}
private static int[] getWidthAndHeight(String text, Font font) {
Rectangle2D r = font.getStringBounds(text, new FontRenderContext(AffineTransform.getScaleInstance(1, 1), false, false));
int unitHeight = (int) Math.floor(r.getHeight());//
// 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
int width = (int) Math.round(r.getWidth()) + 1;
// 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
int height = unitHeight + 3;
System.out.println(“width:” + width + “, height:” + height);
return new int[]{width, height};
}
// 根据str,font的样式以及输出文件目录
public static void createImage(String text, Font font, File outFile)throws Exception {
// 获取font的样式应用在str上的整个矩形
int[] arr = getWidthAndHeight(text, font);
int width = arr[0];
int height = arr[1];
// 创建图片
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);// 创建图片画布
Graphics g = image.getGraphics();
g.setColor(Color.black); // 先用白色填充整张图片,也就是背景 WHITE
g.fillRect(0, 0, width, height);//画出矩形区域,以便于在矩形区域内写入文字
g.setColor(Color.WHITE);// 再换成黑色,以便于写入文字 black
g.setFont(font);// 设置画笔字体
g.drawString(text, 0, font.getSize());// 画出一行字符串
g.drawString(text, 0, 2 * font.getSize());// 画出第二行字符串,注意y轴坐标需要变动
g.dispose();
ImageIO.write(image, “png”, outFile);// 输出png图片
}
/**
* 将本地图片转换成Base64编码
* @param imgFile 待处理图片
* @return
*/
public static String ImgToBase64(String imgFile) {
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return new String(Base64.getEncoder().encode(data));
}
/**
* 将数据库base64编码转成图片
*/
public static void Base64ToImg(String base64ImgData,String filePath) throws IOException {
BASE64Decoder d = new BASE64Decoder();
byte[] bs = d.decodeBuffer(base64ImgData);
FileOutputStream os = new FileOutputStream(filePath);
os.write(bs);
os.close();
}
}