本文实现在图片上添加文字,大家可以百度一下ImageIcon类,在这里就不多介绍了!
这是一个main方法测试:
package test;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import javax.swing.ImageIcon;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class imgAddWords {
public static void main(String[] a) {
String words = "学无止境";// 添加的文字
Color color = Color.yellow;// 文字颜色
imgAddWords.createStringMark("D://a.jpg", words, color, 10, "d://b.jpg");
}
public static boolean createStringMark(String filePath, String words, Color color, float qualNum, String outPath) {
ImageIcon imgIcon = new ImageIcon(filePath);
Image theImg = imgIcon.getImage();
// 获取图片尺寸
int width = theImg.getWidth(null) == -1 ? 200 : theImg.getWidth(null);// 宽
int height = theImg.getHeight(null) == -1 ? 200 : theImg.getHeight(null);// 高
BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
g.setColor(color);
g.setBackground(Color.red);
g.drawImage(theImg, 0, 0, null);// 第二个和第三个参数是截图用的
g.setFont(new Font(null, Font.BOLD, 15)); // 字体、字型、字号
g.drawString(words, 10, height / 4); // 第二个参数横坐标,三个参数纵坐标
g.dispose();
try {
FileOutputStream out = new FileOutputStream(outPath); // 先用一个特定的输出文件名
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(qualNum, true);
encoder.encode(bimage, param);
out.close();
} catch (Exception e) {
return false;
}
return true;
}
}
可以直接复制上面的代码使用,重要的参数都有注释,希望能帮到你们!(不清楚的可以留言问我)