package com.xiaowu.drawwater.demo; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; /** * 在原圖片的基礎之上添加水印效果 * * * * @author WQ * */ public class ImageMarkLogoByIcon { /** * @param args */ public static void main(String[] args) { String srcImgPath = "D:/Test123/car.png"; String iconPath = "D:/Test123/deal.png"; String targerPath = "D:/Test123/img_mark_icon.jpg"; String targerPath2 = "D:/Test123/img_mark_icon_rotate.jpg"; // 給圖片添加水印 ImageMarkLogoByIcon.markImageByIcon(iconPath, srcImgPath, targerPath); // 給圖片添加水印,水印旋轉-45 ImageMarkLogoByIcon.markImageByIcon(iconPath, srcImgPath, targerPath2, -45); } /** * 給圖片添加水印 * @param iconPath 水印圖片路徑 * @param srcImgPath 源圖片路徑 * @param targerPath 目標圖片路徑 */ public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath) { markImageByIcon(iconPath, srcImgPath, targerPath, null); } /** * 給圖片添加水印、可設置水印圖片旋轉角度 * @param iconPath 水印圖片路徑 * @param srcImgPath 源圖片路徑 * @param targerPath 目標圖片路徑 * @param degree 水印圖片旋轉角度 */ public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath, Integer degree) { OutputStream os = null; try { Image srcImg = ImageIO.read(new File(srcImgPath)); BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB); // 得到畫筆對象 // Graphics g= buffImg.getGraphics(); Graphics2D g = buffImg.createGraphics(); // 設置對線段的鋸齒狀邊緣處理 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg .getHeight(null), Image.SCALE_SMOOTH), 0, 0, null); if (null != degree) { // 設置水印旋轉 g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg .getHeight() / 2); } // 水印圖象的路徑 水印一般為gif或者png的,這樣可設置透明度 ImageIcon imgIcon = new ImageIcon(iconPath); // 得到Image對象。 Image img = imgIcon.getImage(); float alpha = 0.4f; // 透明度 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 表示水印圖片的位置 g.drawImage(img, 15, 30, null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.dispose(); os = new FileOutputStream(targerPath); // 生成圖片 ImageIO.write(buffImg, "JPG", os); System.out.println("圖片完成添加Icon印章。。。。。。"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) os.close(); } catch (Exception e) { e.printStackTrace(); } } } }
效果圖:

