`
jarod2008
  • 浏览: 80523 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

给图片加上水印

    博客分类:
  • java
 
阅读更多

public static void saveJPEGImage(BufferedImage bi, File outputFile,
            int quality) throws FileNotFoundException, IOException {
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(outputFile));

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);

        param.setQuality(quality / 100.0f, false);

        encoder.setJPEGEncodeParam(param);

        encoder.encode(bi);

        out.close();
    }

 

 

public static void watermarkImage(File imageFile, String message)
            throws FileNotFoundException, IOException {

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                imageFile));

        BufferedImage bi = ImageIO.read(bis);

        Graphics2D g = (Graphics2D) bi.getGraphics();

        int width = bi.getWidth();

        int height = bi.getHeight();

        Font myFont = new Font("Sans", Font.BOLD, 18);

        Rectangle2D bb = myFont.getStringBounds(message, g
                .getFontRenderContext());

        if (width < bb.getWidth() + 6 || height < bb.getHeight() + 20)
            return;

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                (float) 0.5));

        int x = width - (int) bb.getWidth() - 3;

        int y = height - 10;

        g.setFont(myFont);

        g.setColor(Color.lightGray);

        g.drawString(message, x, y);

        saveJPEGImage(bi, imageFile, 100);
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics