此 Graphics2D 类扩展 Graphics 类,以提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制。它是用于在 Java(tm) 平台上呈现二维形状、文本和图像的基础类。
一、在图片上绘制文字
实例代码:
package com.test.testImage; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Graphics2DTest { public static void main(String[] args) { try { String text = "文字居中"; int width = 500; int height = 400; // 创建BufferedImage对象 BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); // 获取Graphics2D Graphics2D g2d = image.createGraphics(); // 画图 g2d.setBackground(new Color(255,255,255)); //g2d.setPaint(new Color(0,0,0)); g2d.setColor(Color.red); g2d.clearRect(0, 0, width, height); Font font=new Font("宋体",Font.PLAIN,64); g2d.setFont(font); // 抗锯齿 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 计算文字长度,计算居中的x点坐标 ,即字符串左边位置 FontMetrics fm = g2d.getFontMetrics(font); int textWidth = fm.stringWidth(text); int textHeight = fm.getHeight(); int widthX = (width - textWidth) / 2; // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。 // y坐标位置为:指字体所在矩形的左上角y坐标+ascent(基线-升部线的距离) //原本字体基线位置对准画布的y坐标导致字体偏上ascent距离,加上ascent后下移刚好顶边吻合 // int y = (height-textHeight )/2+fm.getAscent(); g2d.drawString(text,widthX,100); //本内容根据实际情况,固定在具体高度位置 // 释放对象 g2d.dispose(); // 保存文件 ImageIO.write(image, "jpg", new File("D:/test.jpg")); } catch(Exception ex) { ex.printStackTrace(); } } }
二、解决服务器部署图片文字乱码问题
在Windows系统上,文字显示正常,当项目部署到Linux系统上时,中文全部变成了口口口这种方框。我们使用的文字是Font font=new Font(“宋体”,Font.PLAIN,64);。出现的原因是因为在Linux上没有中文宋体或者没有中文其他文字的字体库,需要我们导入。
(1)查找Windows系统(本地)的文字包
查找路劲C:\Windows\Fonts 
(2)将ttf文件导入到linux系统java的fonts包中。 
注:路径是你Linux系统java安装的文件,根据你的安装目录查询
(3)重启java或者tomcat生效
API :
https://www.oschina.net/uploads/doc/javase-6-doc-api-zh_CN/java/awt/Graphics2D.html
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/198757.html原文链接:https://javaforall.net
