java给图片添加水印

public class WatermarkUtil {
    public static void markeWatermark(File file, String waterMarkContent, OutputStream outputStream) throws Exception {
        Date time = new Date();
        long startTimes = time.getTime();
        if (file == null
                || !file.isFile()
                || !file.exists()
                || !file.canRead()
                || StringUtils.isBlank(waterMarkContent)) {
            throw new Exception("文件无效");
        }
        // 加水印
        BufferedImage bufImg = ImageIO.read(file);
        int imgWidth = bufImg.getWidth(null);
        int imgHeight = bufImg.getHeight(null);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(bufImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
        g.rotate(Math.toRadians(330), (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2);
        //根据图片的背景设置水印颜色
        g.setColor(Color.gray);
        //设置字体
        g.setFont(new Font("宋体", Font.PLAIN, 20));
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                0.5f));
        for (int x = 50; x < imgHeight; x += 100) {
            for (int y = 75; y < imgWidth; y += 150) {
                //画出水印
                g.drawString(waterMarkContent, y, x);
            }
        }
        ImageIO.write(bufImg, "png", outputStream);
        outputStream.flush();
        outputStream.close();
        time = new Date();
        long endTimes = time.getTime();
        System.out.println("本次水印共用时:"+String.valueOf(endTimes-startTimes)+",文件路径:"+file.getPath()+",文件大小:"+file.length());
    }

    public static void main(String args[]){
        File img = new File("D:/a/123.png");
        try(FileOutputStream os = new FileOutputStream(new File("D:/a/a.png"))){
            markeWatermark(img,"测试",os);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

 



结果展示:

注:出现中文乱码是因为系统没有你所设置的字体,需要将字体的ttf文件拷贝到系统的字体库中

转载于:https://www.cnblogs.com/xiao-OvO-/p/10730324.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值