效果图
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* 作者qq1023732997
*/
public class PictureMerge {
public static void textToImage(String str) {
try {
int width = 390;
int height = 140;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Font font = new Font("黑体", Font.PLAIN, 14);
Graphics g = image.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setFont(font);
Color c = new Color(106, 106, 106);
g.setColor(c);
int fontHeight = (int) font.getSize2D();
// 得到当前的font metrics
FontMetrics metrics = g.getFontMetrics();
int StrPixelWidth = metrics.stringWidth(str); // 字符串长度(像素) str要打印的字符串
int lineSize = (int) Math.ceil(StrPixelWidth * 1.0 / width);// 算出行数
System.out.println(StrPixelWidth + "---:");
if (width < StrPixelWidth) {// 页面宽度(width)小于 字符串长度
StringBuilder sb = new StringBuilder();// 存储每一行的字符串
int j = 0;
int tempStart = 0;
String tempStrs[] = new String[lineSize];// 存储换行之后每一行的字符串
for (int i1 = 0; i1 < str.length(); i1++) {
char ch = str.charAt(i1);
sb.append(ch);
Rectangle2D bounds2 = metrics.getStringBounds(sb.toString(), null);
int tempStrPi1exlWi1dth = (int) bounds2.getWidth();
if (tempStrPi1exlWi1dth > width) {
tempStrs[j++] = str.substring(tempStart, i1);
tempStart = i1;
sb.delete(0, sb.length());
sb.append(ch);
}
if (i1 == str.length() - 1) {// 最后一行
tempStrs[j] = str.substring(tempStart);
}
}
for (int i = 0; i < tempStrs.length; i++) {
g.drawString(tempStrs[i], 5, (fontHeight + 5) * (i + 1));
}
} else {
g.drawString(str, 5, fontHeight);
}
File outputfile = new File("D:\\云上\\686.png");
ImageIO.write(image, "png", outputfile);
g.dispose();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] arg) {
String str = "最近经常看到大家动不动就在“随着身体的一阵颤抖”,画面感极强此人多半是在尬舞吧!那么到底“随着身体的一阵颤抖”是什么梗,“随着身体的一阵颤抖”的出处在哪,一起来看看吧:......";
textToImage(str);
}
}