springboot 给图片加二维码

废话不多说,直接上代码

    @PostMapping("/watermarkImages")
    public String watermarkImages() throws Exception {
        //获取原始图片文件
        String srcImgPath = "F://bg1.png";
        String fileNameType = srcImgPath.substring(srcImgPath.lastIndexOf("."), srcImgPath.length());
        String tarImgPath = CustomConfig.diskLocation + System.currentTimeMillis() + fileNameType; //待存储的地址
        addWaterMark(srcImgPath, tarImgPath);
        return "success";
    }

    /***
     * 在一张背景图上添加二维码
     * @param bigImgPath 背景图的路径
     * @param outPathWithFileName 输出路径
     */
    public void addWaterMark(String bigImgPath, String outPathWithFileName) throws Exception {
        // 读取原图片信息
        File srcImgFile = new File(bigImgPath);//得到文件
        Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
        int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
        int srcImgHeight = srcImg.getHeight(null);//获取图片的高
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        String content = "时光蹉跎看淡岁月你我";
        //使用工具类生成二维码
        Image image = QRCodeUtil.createImages(content);
        //将小图片绘到大图片上,500,300 .表示你的小图片在大图片上的位置。
        g.drawImage(image, 500, 500, null);
        //设置颜色。
        g.setColor(Color.WHITE);
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(outPathWithFileName);
        ImageIO.write(bufImg, "png", outImgStream);
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();
    }


    /***
     * 生成二维码
     * @param content 二维码里面的内容
     */
    public static BufferedImage createImages(String content) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 192, 192, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

经过本人亲测,妥妥的

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值