Java给图片添加文字水印(拿去即用)

根据图片实际宽高自适应调整字号、水印绘制的坐标

package util;
import java.io.* ;
import java.text.DecimalFormat;
import com.sun.image.codec.jpeg.* ;
import java.awt.* ;
import java.awt.image.BufferedImage;
import java.awt.image.* ;
import javax.imageio.ImageIO;
import javax.swing.* ;
import javax.swing.filechooser.FileSystemView;

public class Shuiyin {
	public static void main(String[]args) throws Exception{
		File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
		String desktopPath = desktopDir.getAbsolutePath();
		boolean flag = createMark("你的原图路径", "自定义水印", Color.GRAY, 0.5f);
        System.out.println(flag);
    }
	/**
	 * @param filePath 原图路径
	 * @param markContent 文字水印内容
	 * @param markContentColor 文字水印颜色
	 * @param alpha 文字水印透明度
	 * @return
	 */
    public static boolean createMark(String filePath, String markContent, Color markContentColor, float alpha) {
		DecimalFormat df=new DecimalFormat("0.00");	//避免除法仅保留整数
    	File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
		String desktopPath = desktopDir.getAbsolutePath();	//获取桌面路径
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
        int width = theImg.getWidth(null);
        int height = theImg.getHeight(null);
        System.out.println(width + "  " + height);
        
        BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        g.setColor(markContentColor);
        g.setBackground(Color.white);

        Font f = new Font("黑体", Font.ITALIC, (int) Double.parseDouble(df.format((float)width/5000*240)));
        g.setFont(f);
        g.drawImage(theImg, 0, 0, null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        for (int i = 1; i < 8; i++) {
        	if(i%2 != 0) {
        		g.drawString(markContent, (int)(width / 8 * 0.6), i * height / 8); // 添加水印的文字和设置水印文字出现的内容
        	} else if(i%2 == 0) {
        		g.drawString(markContent, (int)(width / 8 * 2), i * height / 8); // 添加水印的文字和设置水印文字出现的内容
        	}
		}
        g.dispose();
        try {
            FileOutputStream out = new FileOutputStream("你的输出路径");
            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;
    }
    
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值