java图片加水印 博客分类: java基础 javaimagewatermark
程序员文章站
2024-02-14 18:53:52
...
一: 添加文字水印:
/** * Embeds a textual watermark over a source image to produce * a watermarked one. * @param text The text to be embedded as watermark. * @param sourceImageFile The source image file. * @param destImageFile The output image file. */ static void addTextWatermark(String text, File sourceImageFile, File destImageFile) { try { BufferedImage sourceImage = ImageIO.read(sourceImageFile); Graphics2D g2d = (Graphics2D) sourceImage.getGraphics(); // initializes necessary graphic properties AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f); g2d.setComposite(alphaChannel); g2d.setColor(Color.BLUE); g2d.setFont(new Font("Arial", Font.BOLD, 64)); FontMetrics fontMetrics = g2d.getFontMetrics(); Rectangle2D rect = fontMetrics.getStringBounds(text, g2d); // calculates the coordinate where the String is painted int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2; int centerY = sourceImage.getHeight() / 2; // paints the textual watermark g2d.drawString(text, centerX, centerY); ImageIO.write(sourceImage, "png", destImageFile); g2d.dispose(); System.out.println("The tex watermark is added to the image."); } catch (IOException ex) { System.err.println(ex); } }
二:加图片水印:
/** * Embeds an image watermark over a source image to produce * a watermarked one. * @param watermarkImageFile The image file used as the watermark. * @param sourceImageFile The source image file. * @param destImageFile The output image file. */ static void addImageWatermark(File watermarkImageFile, File sourceImageFile, File destImageFile) { try { BufferedImage sourceImage = ImageIO.read(sourceImageFile); BufferedImage watermarkImage = ImageIO.read(watermarkImageFile); // initializes necessary graphic properties Graphics2D g2d = (Graphics2D) sourceImage.getGraphics(); AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f); g2d.setComposite(alphaChannel); // calculates the coordinate where the image is painted int topLeftX = (sourceImage.getWidth() - watermarkImage.getWidth()) / 2; int topLeftY = (sourceImage.getHeight() - watermarkImage.getHeight()) / 2; // paints the image watermark g2d.drawImage(watermarkImage, topLeftX, topLeftY, null); ImageIO.write(sourceImage, "png", destImageFile); g2d.dispose(); System.out.println("The image watermark is added to the image."); } catch (IOException ex) { System.err.println(ex); } }
上一篇: 后端渲染与前端渲染,后端路由与前端路由
下一篇: 物化视图测试手册
推荐阅读
-
SWT 图片背景平铺 博客分类: Java SWT Image 图像 SWTImage图像平铺
-
java图片加水印 博客分类: java基础 javaimagewatermark
-
java模拟浏览器截取指定大小的验证码图片 博客分类: java javaimage
-
Java 中的正则表达式 博客分类: Java基础笔记 正则表达式JavaUnixF#J2SE
-
Java的移位操作 博客分类: Java基础笔记 JavaBlogJ#
-
Java Socket 编程 博客分类: java基础 SocketJavathread
-
Spring AOP 博客分类: Java基础 SpringAOPaspectj
-
java refection 博客分类: java基础 java
-
利用反射获取与修改private的属性的值 博客分类: java基础 javareflect
-
java refection 博客分类: java基础 java