123456d 的博客

记录精彩的程序人生

Java 添加图片水印

今天做了一个IP签名图片,使用图片添加水印的方式

啥也不说了,直接上代码

/**
 * 功能描述 TODO
 *
 * @author luoyuanxiang
 * {@link ImageReorganization}
 * @date  2018/11/1 15:59
 */
public class ImageReorganization {
    public static void main(String[] args) {
        String backgroundPath = "F:\\其他\\图片\\ImageReorganization.jpg";
        String os ="操作系统:Windows 10 x64 Edition";
        String browser = "浏览器:Google Chrome 70.0.3538.77";
        String network = "地址:四川成都市 电信 10.0.0.0";
        String sitName = "随笔一记";
        String domain = "https://www.luoyuanxiangvip.com";
        String outPutPath="F:\\其他\\图片\\2.jpg";
        String base64 = overlapImage(backgroundPath, null, os, browser,network, sitName, domain, outPutPath);
    }

    /**
     *
     * @param backgroundPath 图片原陆军
     * @param qrCodePath 图标
     * @param os 系统信息
     * @param browser 浏览器信息
     * @param network 来源地
     * @param siteName 名称
     * @param domain 域名
     * @param outPutPath 水印图片输出地方
     * @return
     */
    public static String overlapImage(String backgroundPath,String qrCodePath,String os,String browser,String network,String siteName,String domain,String outPutPath){
        String base64 = null;
        try {
            //设置图片大小
            BufferedImage background = resizeImage(1000,618, ImageIO.read(new File(backgroundPath)));
            BufferedImage qrCode = null;
            if(qrCodePath != null) {
                qrCode = resizeImage(150,150,ImageIO.read(new File(qrCodePath)));
            }
            Graphics2D g = background.createGraphics();
            g.setColor(new Color(0, 0, 0,128));
            g.setFont(new Font("微软雅黑",Font.PLAIN,50));
            g.drawString(network,80 ,190);
            g.drawString(os,80 ,260);
            g.drawString(browser,80 ,330);
            g.drawString(siteName,80 ,400);
            g.drawString(domain,80 ,470);
            if(qrCode != null) {
                //在背景图片上添加二维码图片
                g.drawImage(qrCode, 700, 240, qrCode.getWidth(), qrCode.getHeight(), null);
            }
            g.dispose();
            ImageIO.write(background, "jpg", new File(outPutPath));
            base64 = Base64Util.encode(Base64Util.imageTobyte(outPutPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "data:img/jpg;base64," + base64;
    }

    public static BufferedImage resizeImage(int x, int y, BufferedImage bfi){
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(
                bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

这样一个IP签名就搞定了,效果图片

留下你的脚步