1 import java.awt.AlphaComposite; 2 import java.awt.Graphics2D; 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.IOException; 6 7 import javax.imageio.ImageIO; 8 public class NewImageUtils { 9 /** 10 * 11 * @Title: 构造图片 12 * @Description: 生成水印并返回java.awt.image.BufferedImage 13 * @param file 14 * 源文件(图片) 15 * @param waterFile 16 * 水印文件(图片) 17 * @param x 18 * 距离右下角的X偏移量 19 * @param y 20 * 距离右下角的Y偏移量 21 * @param alpha 22 * 透明度, 选择值从0.0~1.0: 完全透明~完全不透明 23 * @return BufferedImage 24 * @throws IOException 25 */ 26 public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException { 27 // 获取底图 28 BufferedImage buffImg = ImageIO.read(file); 29 // 获取层图 30 BufferedImage waterImg = ImageIO.read(waterFile); 31 // 创建Graphics2D对象,用在底图对象上绘图 32 Graphics2D g2d = buffImg.createGraphics(); 33 int waterImgWidth = waterImg.getWidth();// 获取层图的宽度 34 int waterImgHeight = waterImg.getHeight();// 获取层图的高度 35 // 在图形和图像中实现混合和透明效果 36 g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); 37 // 绘制 38 g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null); 39 g2d.dispose();// 释放图形上下文使用的系统资源 40 return buffImg; 41 } 42 43 /** 44 * 输出水印图片 45 * 46 * @param buffImg 47 * 图像加水印之后的BufferedImage对象 48 * @param savePath 49 * 图像加水印之后的保存路径 50 */ 51 private void generateWaterFile(BufferedImage buffImg, String savePath) { 52 int temp = savePath.lastIndexOf(".") + 1; 53 try { 54 ImageIO.write(buffImg, savePath.substring(temp), new File(savePath)); 55 } catch (IOException e1) { 56 e1.printStackTrace(); 57 } 58 } 59 60 /** 61 * 62 * @param args 63 * @throws IOException 64 * IO异常直接抛出了 65 * @author bls 66 */ 67 public static void main(String[] args) throws IOException { 68 String sourceFilePath = "D://img//di.png"; 69 String waterFilePath = "D://img//ceng.png"; 70 String saveFilePath = "D://img//new.png"; 71 NewImageUtils newImageUtils = new NewImageUtils(); 72 // 构建叠加层 73 BufferedImage buffImg = NewImageUtils.watermark(new File(sourceFilePath), new File(waterFilePath), 0, 0, 1.0f); 74 // 输出水印图片 75 newImageUtils.generateWaterFile(buffImg, saveFilePath); 76 } 77 }
时间: 2024-10-17 21:32:25