代码
public class ImageUtils {
public boolean createMark(String filePath, String markContent,
Color markContentColor, float qualNum) {
ImageIcon imgIcon = new ImageIcon(filePath);
Image theImg = imgIcon.getImage();
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
BufferedImage bimage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimage.createGraphics();
Font font = new Font("黑体", Font.PLAIN, 20);
g.setColor(markContentColor);
g.setBackground(Color.white);
g.setFont(font);
g.drawImage(theImg, 0, 0, null);
String[] strs=markContent.split(";");
for (int i = 0; i < strs.length; i++) {
FontMetrics metrics = g.getFontMetrics(g.getFont());//获得文字的高
int fontHeight=metrics.getHeight();
int x=width/2 + width/17;
int y=height/2 + height/3+fontHeight*i;
g.drawString(strs[i],x,y); // 添加水印的文字和设置水印文字出现的内容
}
g.dispose();
try {
FileOutputStream out = new FileOutputStream(filePath);
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;
}
public static void main(String[] args) {
ImageUtils imgUtil = new ImageUtils();
imgUtil.createMark("E:/1.jpg", "此图片来自百度", Color.red, 1.0f);
}
}