效果图:
public static void addWaterMark(File inputFile, File outputFile, String text) throws IOException { Image image = ImageIO.read(inputFile); int imgWidth = image.getWidth(null);// 获取图片的宽 int imgHeight = image.getHeight(null);// 获取图片的高 int angel = 315;//旋转角度 int xpadding = 40;//每个水印水平间隔 int ypadding = 40;//每个水印垂直间隔 int fontSize = 10; BufferedImage bi = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //绘制原图片 float alpha = 1F; AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha); g.setComposite(ac); g.drawImage(image, 0, 0, imgWidth, imgHeight, null); g.setBackground(Color.BLACK); //开始绘制水印 //水印字体 Font font = new Font("微软雅黑", Font.BOLD, fontSize); g.setFont(font); FontRenderContext frc = g.getFontRenderContext(); TextLayout tl = new TextLayout(text, font, frc); //水印串宽度 int stringWidth = g.getFontMetrics(g.getFont()).charsWidth(text.toCharArray(), 0, text.length()); //旋转水印 g.rotate(Math.toRadians(angel), (double) imgWidth / 2, (double) imgHeight / 2); //水印透明度 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5F)); // 字体色 g.setColor(Color.RED); int x = -imgHeight / 2; int y = -imgWidth / 2; //循环绘制 while (x < imgWidth + imgHeight / 2) { y = -imgWidth / 2; while (y < imgHeight + imgWidth / 2) { Shape sha = tl.getOutline(AffineTransform.getTranslateInstance(x, y)); g.fill(sha); y += ypadding; } x += stringWidth + xpadding; } //释放资源 g.dispose(); ImageIO.write(bi, "PNG", outputFile); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)