画像に透かしを付ける


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;
        }
    }