给图片加水印(JSP)

繁简对译:[]  字体设置:[] 2008-10-14  阅读  次

给图片加水印(JSP)

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import com.sun.image.codec.jpeg.*;
public class WaterMark {
    /**
      * 给图片添加水印
    * @param filePath 需要添加水印的图片的路径
    * @param markContent 水印的文字
    * @param markContentColor 水印文字的颜色
    * @param qualNum 图片质量
    * @return
    */
    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);
       
       
//      水印图片
        ImageIcon imgIcon1=new ImageIcon("f://ee.gif");
        Image theImg1 =imgIcon1.getImage();
     
       
       
        Graphics2D g=bimage.createGraphics();
        g.setColor(markContentColor);
        g.setBackground(Color.white);
        g.drawImage(theImg, 0, 0, null );
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1f)); //添加图片水印
        g.drawImage(theImg1,0,0,null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
//        g.drawString(markContent,width-200,height-10); //添加水印的文字和设置水印文字出现的内容 和位置
        g.dispose();
        try{
        FileOutputStream out=new FileOutputStream(filePath);
        JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
        encoder.encode(bimage);
        out.close();
        }catch(Exception e)
        { return false; }
        return true;
    }
    public static void main(String[] args) {
    WaterMark wm = new WaterMark();
    if (wm.createMark("f://yy.jpg","<h1>[url]http://www.free-120.com[/url]<h1>",Color.RED,80f))
    {
        System.out.println("添加水印成功!");
    }
    else
    {
        System.out.println("添加水印失败!");
    }
}
}

打印 收藏 关闭