给图片添加水印文字

有一个问题,就是fontsize字体的大小设置,因为不同图片像素不同,所以不知道怎么根据像素来设置字体大小。

/**
 * 给图片添加水印文字、可设置水印文字的旋转角度
 * @param logoText
 * @param srcImgPath
 * @param targerPath
 * @param degree
 * @param fontsize
 */
public static boolean addImgWater(String logoText, String srcImgPath, String targerPath, Integer degree, int fontsize) {
    InputStream is = null;
    OutputStream os = null;
    try {
        //获取后缀
        String ext = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1);
        // 1、源图片
        BufferedImage srcImg = ImageIO.read(new File(srcImgPath));
        int imgwidth = srcImg.getWidth(null);
        int imgheight = srcImg.getHeight(null);
        BufferedImage buffImg = new BufferedImage(imgwidth,imgheight, BufferedImage.TYPE_INT_RGB);
        // 2、得到画笔对象
        Graphics2D g = buffImg.createGraphics();
        // 3、设置对线段的锯齿状边缘处理
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(srcImg, 0, 0, null);
        // 4、设置水印旋转
        if (null != degree) {
            g.rotate(Math.toRadians(degree),
                    (double) buffImg.getWidth() / 2,
                    (double) buffImg.getHeight() / 2);
        }
        // 5、设置水印文字颜色
        //Color color = new Color(205,205,205);
        g.setColor(Color.red);
        // 6、设置水印文字Font
        Font font = new Font("宋体",Font.BOLD, fontsize);
        g.setFont(font);
        // 7、设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.2f));
        // 8、第一参数:设置的内容,后面两个参数:文字在图片上的坐标位置
        int positionWidth = buffImg.getWidth()/5;
        int positionHeight = buffImg.getHeight()/2;
        g.drawString(logoText, positionWidth, positionHeight);
        // 9、释放资源
        g.dispose();
        // 10、生成图片
        os = new FileOutputStream(targerPath);
        ImageIO.write(buffImg, ext, os);
        System.out.println("图片完成添加水印文字");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != is)
                is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (null != os)
                os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yangymy/article/details/80541197