java画图工具来添加水印

用Java代码给图片加水印

不多哔哔,直接上代码:

    /**
     * @param srcImgFile       原图片文件对象
     * @param outFile          输出图片文件对象
     * @param waterMarkContent 水印内容
     * @param markContentColor 水印颜色 * @param rate 字体间距 * @param x x轴位置 * @param y y轴位置 * @param font 字体 */ public static void addWaterMark(File srcImgFile, File outFile, String waterMarkContent, Color markContentColor, double rate, int x, int y, Font font) { try { // 读取原图片信息 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(); // 创建Graphics2D画笔对象 g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null); g.setColor(markContentColor); //根据图片的背景设置水印颜色 g.setFont(font); //设置字体 WaterMarkUtils.MyDrawString(waterMarkContent,x,y,rate,g); // 设置字体间距加输出 g.dispose(); // 进行处理 // 输出图片 FileOutputStream outImgStream = new FileOutputStream(outFile); // 创建文件输出流 ImageIO.write(bufImg, "jpg", outImgStream); System.out.println("添加水印完成"); outImgStream.flush(); // 刷新文件 outImgStream.close(); // 释放资源 } catch (Exception e) { System.out.println("异常"); e.printStackTrace(); } } 

设置字体间距

这个是在百度上找的,原贴的地址https://blog.csdn.net/zixiaomuwu/article/details/51068698

    /**
     * 设置字体间距加输出
     * @param str  输出字符串
     * @param x    x轴
     * @param y    y轴
     * @param rate 字体间距 * @param g 画笔对象 */ public static void MyDrawString(String str,int x,int y,double rate,Graphics2D g){ String tempStr=new String(); int orgStringWight=g.getFontMetrics().stringWidth(str); int orgStringLength=str.length(); int tempx=x; int tempy=y; while(str.length()>0) { tempStr=str.substring(0, 1); str=str.substring(1, str.length()); g.drawString(tempStr, tempx, tempy); tempx=(int)(tempx+(double)orgStringWight/(double)orgStringLength*rate); } } 
 来源: 锌闻网

猜你喜欢

转载自www.cnblogs.com/1994jinnan/p/13369520.html