代码:
public static void main(String[] args) throws IOException {
Color color=new Color(255,0,0);
Font font = new Font("微软雅黑", Font.BOLD, 40);
waterMark("E:\\1\\333.jpg", "E:\\2\\waterMark.jpg","水印",color,font,60,60);
}
/**
* @param filePath 原图片
* @param outFile 输出图片
* @param text 水印文字
* @param color 颜色
* @param font 字体
* @param x 水印起始X坐标
* @param y 水印起始Y坐标
* @return 添加水印是否成功 true-成功 false-失败
*/
public static boolean waterMark(String filePath, String outFile,
String text, Color color, Font font, int x, int y) {
FileInputStream in = null;
try {
in = new FileInputStream(filePath);
BufferedImage im = ImageIO.read(in);
int width = im.getWidth();
int height = im.getHeight();
if (x > width || y > height) {
return false;
}
Graphics g = im.getGraphics();
g.setColor(color);
g.setFont(font);
g.drawString(text, x, y);
g.dispose();
ImageIO.write(im, "jpg", new File(outFile));
} catch (IOException e) {
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
运行效果: