java图片添加水印

  /**
 * 添加水印的图片地址, 水印图片地址, 输出地址, 水印旋转度数
 * @param iconPath 添加水印的图片地址
 * @param srcImagePath 水印图片地址
 * @param targerPath 输出地址
 * @param degree 水印旋转度数
 * @return
 */
public static boolean markImageByIcon(String iconPath, String srcImagePath,
        String targerPath, Integer degree) {
    OutputStream os = null;
    try {
        Image srcImage = ImageIO.read(new File(srcImagePath));
        BufferedImage bufferImg = new BufferedImage(
                srcImage.getWidth(null), srcImage.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferImg.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(srcImage.getScaledInstance(srcImage.getWidth(null),
                srcImage.getHeight(null), BufferedImage.TYPE_INT_RGB), 0,
                0, null);
        if (null != degree) {
            g.rotate(Math.toDegrees(degree),
                    (double) bufferImg.getWidth() / 2,
                    (double) bufferImg.getHeight() / 2);
        }
        
        ImageIcon imageIcon = new ImageIcon(iconPath);
        Image img = imageIcon.getImage();
        
        float alpha = 0.5f;
        
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
    
        g.drawImage(img, 150, 300, null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        g.dispose();
        os = new FileOutputStream(targerPath);
        ImageIO.write(bufferImg, "JPG", os);
        
    } catch (IOException e) {
        System.out.println("添加水印时出现异常");
    } finally{
        if(null != os){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容