java 添加文字水印

package com.lzzj.prodma.controllers.archives;

import java.awt.Color;
import java.io.File;

import com.lowagie.text.Font;

public interface MarkService {
	public  String MARK_TEXT="我的公司";
	public  String FONT_NAME="微软雅黑";
	public  int FONT_STYLE=Font.BOLD;
	public  int FONT_SIZE=40;
	public  Color FONT_COLOR=Color.GRAY;
	//static final
	public static final int X=10;
	public static final int Y=10;
	
	public static float ALPHA=0.3F;
	
	public String watermark(File image,String imageFileName,String uploadPath,String realUploadPath);
	
}

package com.lzzj.prodma.controllers.archives;

import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class TextMarkService implements MarkService {
	@Override
	public String watermark(File image,String imageFileName,String uploadPath,String realUploadPath){
		String logoFileName="logo_"+imageFileName;
		OutputStream os=null;
		try {
			Image image2=ImageIO.read(image);
			int width=image2.getWidth(null);
			int height=image2.getHeight(null);
			
			BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
			
			Graphics2D g=bufferedImage.createGraphics();
			
			g.drawImage(image2, 0, 0, width, height, null);
			
			g.setFont(new Font(FONT_NAME,FONT_STYLE,FONT_SIZE));
			g.setColor(FONT_COLOR);
			
			int width1=FONT_SIZE*getTextLength(MARK_TEXT);
			int height1=FONT_SIZE;
			
			int widthDiff=width-width1;
			int heightDiff=height-height1;
			
			
			int x=width-10-width1;
			int y=height-10-height1;
		/*	if(x>widthDiff){
				x=widthDiff;
			}
			if(y>heightDiff){
				y=heightDiff;
			}*/
			
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
			
			g.drawString(MARK_TEXT, x, y+FONT_SIZE);
			g.dispose();
			
			os=new FileOutputStream(realUploadPath+"/"+logoFileName);
			JPEGImageEncoder en= JPEGCodec.createJPEGEncoder(os);
			en.encode(bufferedImage);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(os!=null){
				try {
					os.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
		
		return uploadPath+"/"+logoFileName;
	}
	
	public int getTextLength(String text){
		int length=text.length();
		
		for(int i=0;i1){
				length++;
			}
		}
		
		length=length%2==0?length/2:length/2+1;
		return length;
		
	}
	public static void main(String[] args){
		TextMarkService tms=new TextMarkService();
		File image=new File("C:/logs/132999/3.JPG");
		String aa=tms.watermark(image,"3.JPG","C:/logs/132999","C:/logs/132999");
	}
}

你可能感兴趣的:(java)