利用java程序给图片打水印

代码

public class ImageUtils {

     public boolean createMark(String filePath, String markContent,
            Color markContentColor, float qualNum) {
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
        int width = theImg.getWidth(null);
        int height = theImg.getHeight(null);
        BufferedImage bimage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        Font font = new Font("黑体", Font.PLAIN, 20);
        g.setColor(markContentColor);
        g.setBackground(Color.white);
        g.setFont(font);
        g.drawImage(theImg, 0, 0, null);
        String[] strs=markContent.split(";");
        for (int i = 0; i < strs.length; i++) {
            FontMetrics metrics = g.getFontMetrics(g.getFont());//获得文字的高
            int fontHeight=metrics.getHeight();
            int x=width/2 + width/17;
            int y=height/2 + height/3+fontHeight*i;
            g.drawString(strs[i],x,y); // 添加水印的文字和设置水印文字出现的内容
        }
        g.dispose();
        try {
            FileOutputStream out = new FileOutputStream(filePath);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
            param.setQuality(qualNum, true);
            encoder.encode(bimage, param);
            out.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

       public static void main(String[] args) {
         ImageUtils imgUtil = new ImageUtils();
         imgUtil.createMark("E:/1.jpg", "此图片来自百度", Color.red, 1.0f);
       }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值