您的位置:首页 > 编程语言 > Java开发

Java实现在图片上添加水印图片和水印文字

2009-08-09 00:11 1146 查看
public static void main(String[] args)
{
createMark("e://image//a.gif","e://image//b.jpg");
}

/**
* 在图片上添加水印图片和文字
* @param filePath 原图片文件路径
* @param watermark 水印图片文件路径
* @return 添加成功返回true,否则返回false
*/
public static boolean createMark(String filePath, String watermark)
{
//读取原图片
ImageIcon imgIcon = new ImageIcon(filePath);
Image theImg = imgIcon.getImage();
//读取标签图片
ImageIcon waterIcon = new ImageIcon(watermark);
Image waterImg = waterIcon.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("SansSerif",Font.BOLD,30);
g.setFont(font);
//设置前景色
g.setColor(Color.red);
//设置背景色
g.setBackground(Color.white);
//画原图
g.drawImage(theImg, 0, 0, null);
//画水印图
g.drawImage(waterImg, 100, 100, null);
//画字
g.drawString("中国人民共和国", 10, 10);
g.dispose();
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(50f, true);
encoder.encode(bimage, param);
}
catch (Exception e)
{
return false;
}
finally
{
if(out!=null)
{
try
{
out.close();
out = null;
}
catch(Exception e)
{}
}
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐