- 需求:将文字与图片进行结合,可调整文字间距并且第二行居右
- 代码实现
public static void main(String[] args) {
Integer size = 80;
String str = "测试测试测试测试测试";//待绘制文字
String backImgUrlStr = "http://image.g2s.cn/zhs_yanfa_150820/ablecommons/demo/202009/e3126204331e433c82794d1534702d9c.jpg";
String serverUploadImgUrl = "D:"; // 图片保存路径
// setPictures(size, str, backImgUrlStr, serverUploadImgUrl);
try {
InputStream backImgUrl = new URL(backImgUrlStr).openStream();
BufferedImage backImg = ImageIO.read(backImgUrl);
Font fTxtBottom = new Font("黑体", Font.PLAIN, size);
Color myColorTxtBottom = new Color(51,51,51);
int srcImgHeight = backImg.getHeight();// 背景图片高度度
writeTextCenter(backImg,srcImgHeight / 9 *4,str,fTxtBottom,myColorTxtBottom,11);
String imgName = new Date().getTime() + ".jpg"; //生成的图片名称
File newFile = new File(serverUploadImgUrl, imgName); //生成新的图片
// 此处要写PNG否则可能会出现遮罩层
ImageIO.write(backImg, "png", newFile);
}catch (Exception e) {
}
}
public static BufferedImage writeTextCenter(BufferedImage inputImage, int y, String text, Font font, Color color, Integer length) throws Exception {
Graphics2D graphics2d = inputImage.createGraphics();
//设置文字
setText(inputImage, y, text, font, color, graphics2d, length, 1);
graphics2d.dispose();
return inputImage;
}
private static void setText(BufferedImage inputImage, int y, String text, Font font, Color color, Graphics2D graphics2d, Integer length, Integer count) {
String start = "";
String end = "";
Double rate = 1.13;
if (text.length() > length) {
start = text.substring(0, length);
end = text.substring(length, text.length());
} else {
start = text;
}
graphics2d.setFont(font);
graphics2d.setColor(color);
graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fontMetrics = graphics2d.getFontMetrics(font);
// 计算出中心点,并且绘制出文字
double width = inputImage.getWidth()/2;
//字体长度
double textWidth = rate*graphics2d.getFontMetrics().stringWidth(start)/2;
Integer x = (int)(width-textWidth);
//设置右对齐
if (count != 1) {
double textMaxWidth = textWidth / start.length() * length - textWidth;
if (textMaxWidth > 0) {
//重新计算出中心点 x 位置
x = (int)(width-textWidth+textMaxWidth);
}
}
//设置间距
MyDrawString(start,x,y,rate,graphics2d);
// graphics2d.drawString(start, x, y);
count++;
if (StringUtils.isNotBlank(end)) {
//获取文字高度
int height = fontMetrics.getAscent() + fontMetrics.getDescent();
y += height + 30;
setText(inputImage, y, end, font, color, graphics2d, length, count);
}
}
//设置间距
public static void MyDrawString(String str, int x, int y, double rate, Graphics g) {
String tempStr = new String();
int orgStringWight = g.getFontMetrics().stringWidth(str);
int orgStringLength = str.length();
int tempx = x;
int tempy = y;
while (str.length() > 0) {
tempStr = str.substring(0, 1);
str = str.substring(1, str.length());
g.drawString(tempStr, tempx, tempy);
tempx = (int) (tempx + (double) orgStringWight / (double) orgStringLength * rate);
}
}