import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class WatermarkUtil {
/** * 把图片印刷到图片上 * @param pressImg -- 水印文件 * @param targetImg -- 目标文件 * @param x -- x偏移量 * @param y -- y偏移量 */ public final static void pressImage(String pressImg, String targetImg, int x, int y) { FileOutputStream out = null; try { File targetFile = new File(targetImg); Image imgTarget = ImageIO.read(targetFile); int width = imgTarget.getWidth(null); int height = imgTarget.getHeight(null); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(imgTarget, 0, 0, width, height, null);
// 水印文件 File pressFile = new File(pressImg); Image imgPress = ImageIO.read(pressFile); int widthPress = imgPress.getWidth(null); int heightPress = imgPress.getHeight(null); g.drawImage(imgPress, width - widthPress - x, height - heightPress - y, widthPress, heightPress, null); g.dispose(); out = new FileOutputStream(targetImg); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) try{out.close();} catch(Exception e){}; } }
/** * 打印文字水印图片 * * @param pressText -- 文字 * @param targetImg -- 目标图片 * @param fontName -- 字体名 * @param fontStyle -- 字体样式 * @param color -- 字体颜色 * @param fontSize -- 字体大小 * @param x -- x偏移量 * @param y -- y偏移量 */
public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, int color, int fontSize, int x, int y) { FileOutputStream out = null; try { File targetFile = new File(targetImg); Image imgTarget = ImageIO.read(targetFile); int width = imgTarget.getWidth(null); int height = imgTarget.getHeight(null); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(imgTarget, 0, 0, width, height, null); g.setColor(Color.RED); g.setFont(new Font(fontName, fontStyle, fontSize));
g.drawString(pressText, width - fontSize - x, height - fontSize / 2 - y); g.dispose(); out = new FileOutputStream(targetImg); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) try{out.close();} catch(Exception e){}; } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub pressText("蒙奇D路飞", "d:/EDM.jpg", "宋体", Font.ITALIC, 0xFF0000, 16, 200, 10); //pressImage("d:/createShopMarker.png", "d:/EDM.jpg", 200, 10); }
} |