【可以在eclipse中新建个Utils类,把以下代码复制进去直接使用,以下方法实现单个或多个水印的添加】
package com.rzxt.fyx.common.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
* 给图片添加水印
* @author tgy
*
*/
public class MarkImageUtils {
/**
* @param args
*/
public static void main(String[] args) {
String output = "F:/images/";
String source = "F:/images/6.jpg"; //源图片路径
String icon = "F:/images/icon2.png"; //覆盖图片路径
String imageName = "mark_image"; //图片名称
String imageType = "jpg"; //图片类型jpg,jpeg,png,gif
String text = "加水印了";
int size = 4; //马赛克大小
Integer degree = null; //水印旋转角度-45,null表示不旋转
String result = null;
//给图片添加图片水印
result = MarkImageUtils.markImageByMoreIcon(icon,source,output,imageName,imageType,degree);
// result = MarkImageUtils.markImageBySingleIcon(icon, source, output, imageName, imageType, degree);
// //给图片添加文字水印
// result = MarkImageUtils.markImageByMoreText(source,output,imageName,imageType,Color.red,text,degree);
// result = MarkImageUtils.markImageBySingleText(source,output,imageName,imageType,Color.red,text,degree);
// //给图片打马赛克
// result = MarkImageUtils.markImageByMosaic(source,output,imageName,imageType,size);
System.out.println(result);
}
/**
* 给图片不同位置添加多个图片水印、可设置水印图片旋转角度
* @param icon 水印图片路径(如:F:/images/icon.png)
* @param source 没有加水印的图片路径(如:F:/images/6.jpg)
* @param output 加水印后的图片路径(如:F:/images/)
* @param imageName 图片名称(如:11111)
* @param imageType 图片类型(如:jpg)
* @param degree 水印图片旋转角度,为null表示不旋转
*/
public static String markImageByMoreIcon(String icon,String source,String output,String imageName,String imageType,Integer degree) {
String result = "添加图片水印出错";
try {
File file = new File(source);
File ficon = new File(icon);
if (!file.isFile()) {
return source + " 不是一个图片文件!";
}
//将icon加载到内存中
Image ic = ImageIO.read(ficon);
//icon高度
int icheight = ic.getHeight(null);
//将源图片读到内存中
Image img = ImageIO.read(file);
//图片宽
int width = img.getWidth(null);
//图片高
int height = img.getHeight(null);
BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//创建一个指定 BufferedImage 的 Graphics2D 对象
Graphics2D g = bi.createGraphics();
//x,y轴默认是从0坐标开始
int x = 0;
int y = 0;
//默认两张水印图片的间隔高度是水印图片的1/3
int temp = icheight/3;
int space = 1;
if(height>=icheight){
space = height/icheight;
if(space>=2){
temp = y = icheight/2;
if(space&#