public void mark(String srcImgPath, String outImgPath, Color markContentColor, String waterMarkContent,Integer degree) { try { // 读取原图片信息 File srcImgFile = new File(srcImgPath); Image srcImg = ImageIO.read(srcImgFile); int srcImgWidth = srcImg.getWidth(null); int srcImgHeight = srcImg.getHeight(null); // 加水印 BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufImg.createGraphics(); g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); //Font font = new Font("Courier New", Font.PLAIN, 12); Font font = new Font("黑体", Font.BOLD, 50); g.setColor(markContentColor); //根据图片的背景设置水印颜色 g.setFont(font); // int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3; // int y = srcImgHeight - 3; //设置文字在图片上居中 int x = (srcImgWidth - getWatermarkLength(waterMarkContent, g)) / 2; int y = srcImgHeight / 2; //设置水印旋转 if (null != degree) { g.rotate(Math.toRadians(degree), (double) bufImg.getWidth() / 2, (double) bufImg .getHeight() / 2); } // 7、设置水印文字透明度 float alpha = 0.8f; // 透明度;1.0f为不透明 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha)); //第一参数->水印的内容,后面两个参数->文字在图片上的坐标位置(x,y) g.drawString(waterMarkContent,x, y); //释放资源 g.dispose(); // 输出图片 FileOutputStream outImgStream = new FileOutputStream(outImgPath); ImageIO.write(bufImg, "jpg", outImgStream); outImgStream.flush(); outImgStream.close(); } catch (Exception e) { e.printStackTrace(); } } public int getWatermarkLength(String waterMarkContent, Graphics2D g) { return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length()); }
时间: 2024-11-07 04:13:53