参考:
使用Java给图片加上水印,设置水印的透明度,设置水印的所在位置,位置一共支持:
TOP_LEFT:顶部靠左
TOP_CENTER:顶部居中
TOP_RIGHT:顶部靠右
CENTER_LEFT:中间靠左
CENTER:中间
CENTER_RIGHT:中间靠右
BOTTOM_LEFT:底部靠左
BOTTOM_CENTER:底部居中
BOTTOM_RIGHT:底部靠右
水印的图片,根据原图片的大小等比例缩放,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
private int[] resize(int width, int height){ int wmwidth = this.watermarkImg.getWidth(); int wmheight = this.watermarkImg.getHeight(); int drawWidth = width; int drawHeight = height; double sourceRatio = (double) wmwidth / (double) wmheight; double targetRatio = (double) width / (double) height; if (Double.compare(sourceRatio, targetRatio) != 0) { if (sourceRatio > targetRatio) { //drawHeight = (int) Math.round(wmwidth / sourceRatio); drawHeight = (int) (drawWidth * wmheight / wmwidth); } else { //drawWidth = (int) Math.round(wmheight * sourceRatio); drawWidth = wmwidth * drawHeight / wmheight; } } this.watermarkImg = Utils.createImage(this.watermarkImg, drawWidth, drawHeight, null); int[] size = {drawWidth, drawHeight}; return size; } |
给原图片加上水印,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public BufferedImage apply(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); BufferedImage imgWithWatermark = Utils.createImage(img, width, height, null); int watermarkWidth = watermarkImg.getWidth(); int watermarkHeight = watermarkImg.getHeight(); Point p = position.calculate(width, height, watermarkWidth, watermarkHeight, 0, 0, 0, 0); Graphics2D g = imgWithWatermark.createGraphics(); // Draw the actual image. g.drawImage(img, 0, 0, null); // Draw the watermark on top. g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); g.drawImage(watermarkImg, p.x, p.y, null); g.dispose(); return imgWithWatermark; } |
生成水印图片:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
String str = ImageUtilsTest.class.getResource("/images/org.png").getPath(); File orgPng = new File(str); str = ImageUtilsTest.class.getResource("/images/watermarkater.png").getPath(); BufferedImage watermarkImage = ImageIO.read(new File(str)); Watermark watermark = new Watermark(Positions.CENTER, watermarkImage, 0.6f); ImageUtils.fromFile(orgPng) .scale(1) .watermark(watermark) .toFile(new File("d:\\image\\test.png")); //指定多个水印 Watermark watermark2 = new Watermark(Positions.BOTTOM_CENTER, watermarkImage, 0.6f); ArrayList<Watermark> list = new ArrayList<Watermark>(); list.add(watermark); list.add(watermark2); ImageUtils.fromFile(orgPng) .scale(1) .watermarkArray(list) .toFile(new File("d:\\image\\testMul.png")); |
原图为:
水印:
下载:前往下载
演示:Demo
很好