`
alyouge
  • 浏览: 190638 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

图片加水印

    博客分类:
  • j2ee
阅读更多
public byte[] pressImage(String waterImgPath, byte[] targetImg) throws Exception {
        try {
            InputStream is = new ByteArrayInputStream(targetImg);
            Image src = ImageIO.read(is);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);

            // 水印文件
            File waterFile = new File(waterImgPath);
            Image waterImg = ImageIO.read(waterFile);
            int w = waterImg == null ? 0 : waterImg.getWidth(null);
            int h = waterImg == null ? 0 : waterImg.getHeight(null);

            g.setComposite(AlphaComposite
                    .getInstance(AlphaComposite.SRC_OVER, 0.2f));
            int sw = (width % w) /(width / w + 1);//填充水印图片横向间距
            int sh = (height % h) /(height / h + 1);//填充水印图片纵向间距
            for(int i = sw; i + w + sw <= width; i += w + sw) {
                for (int j = sh; j + h + sh <= height; j += h + sh) {
                    g.drawImage(waterImg, i, j, null);
                }
            }

            g.dispose();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", out);
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics