直接上代码
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
public class AddTextToImg {
public static void main(String[] args) {
String filePath = "D:\\学习\\pro_qrcode.png";
String outPath = "d:\\宋体.png"; //第一次加字
String word2 = "d:\\word2.png";
String webFilePath_word3 = "d:\\word3.png";
drawTextInImg(filePath, "阿尔法蛋AI故事机-用爸爸妈妈的声音讲故事", outPath, 60, 755, "black", 24.0f);//在图片上加商品标题(简介)
drawTextInImg(outPath, "¥3199", word2, 90, 870, "red", 45.0f);//在图片上加商品价格
drawTextInImg(word2, "原价:3399", webFilePath_word3, 225, 865, "black", 20.0f);//在图片上加商品原价
System.out.println("Hello World!");
}
public static void drawTextInImg(String filePath, String text, String outPath,int left_n, int top_n,String color,float fsize) {
ImageIcon imgIcon = new ImageIcon(filePath);
Image img = imgIcon.getImage();
int width = img.getWidth(null);
int height = img.getHeight(null);
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
int fontSize = (int)fsize; //字体大小
int rectX = left_n;
int rectY = top_n;
int rectWidth = text.length() * (fontSize + 30);
int rectHeight = fontSize + 8;
Font font = new Font("宋体",Font.BOLD, fontSize); //定义字体
g.setBackground(Color.white);
g.drawImage(img, 0, 0, null);
if("black".equals(color)){
g.setPaint(Color.black);
}else if("red".equals(color)){
g.setPaint(Color.red);
}
g.setFont(font);
//g.drawRect(left_n, top_n, rectWidth, rectHeight);
g.drawString(text, rectX, top_n);
g.dispose();
try {
FileOutputStream out = new FileOutputStream(outPath);
ImageIO.write(bimage, "png", out);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}