JAVA生成带图标的二维码(产品溯源码)

一、效果图
在这里插入图片描述
二、代码示例:

1. 引入依赖

<!--谷歌提供的二维码插件-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.3</version>
        </dependency>

2. 底层+图标图片
底层图片
图标
3. 创建二维码
①工具类:QRCodeUtil

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author matx
 * @description:  生成二维码
 * @date 2022/8/1814:02
 */
public class QRCodeUtil {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //二维码颜色
    private static final int BLACK = 0xFF000000;
    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * @param text    请求地址
     * @param width   图片长度
     * @param height  图片高度
     * @param logoPath logo路径
     * @param code    溯源码唯一code
     * @param smallLogo    最中间的logo
     * @param formatName 最终文件形式
     */
    public static String createImg(String text, int width, int height,
                                            String logoPath,String code,String formatName,String smallLogo) {
        Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
        //设置编码字符集
        his.put(EncodeHintType.CHARACTER_SET, "utf-8");
        String resultPath = "";
        try {
            //1、生成二维码
            BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);
            //2、获取二维码宽高
            int codeWidth = encode.getWidth();
            int codeHeight = encode.getHeight();
            //3、将二维码放入缓冲流
            BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < codeWidth; i++) {
                for (int j = 0; j < codeHeight; j++) {
                    //4、循环将二维码内容定入图片
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
                }
            }
            //设置圆角
            image = setClip(image, 400);
//            String fileName = filePath + code+".jpg";
            String fileName = code + ".jpg";
            //5、将二维码写入图片
            File outPutImage = new File(fileName);
            // 构建绘图对象
            Graphics2D g = image.createGraphics();
            // 读取网络Logo图片
            URL smallUrl = new URL(smallLogo);
            // 读取本地Logo图片
            //BufferedImage logo = ImageIO.read(new File(smallLogo));
            // 读取网络Logo图片
            BufferedImage logo = ImageIO.read(smallUrl);
            // 开始绘制logo图片
            g.drawImage(logo, image.getWidth() * 2 / 5, image.getHeight() * 2 / 5, image.getWidth() * 2 / 10, image.getHeight() * 2 / 10, null);
            g.dispose();
            logo.flush();
            image.flush();
            ImageIO.write(image, "jpg", outPutImage);
            System.out.println("二维码生成成功");
            //resultPath = filePath + code + ".jpg";
            resultPath = code + ".jpg";
            //二维码嵌入底层logo
            resultPath = mergeImage(logoPath, fileName, resultPath, formatName);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("二维码图片生成失败");
        }
        return resultPath;
    }

    /**
     * 图片切圆角
     * @param srcImage
     * @param radius
     * @return
     */
    public static BufferedImage setClip(BufferedImage srcImage, int radius) {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }
    /**
     * 将二维码写入到logo文件中
     * @param logoPath  logo文件地址
     * @param qrPath    生成的二维码存放地址
     * @param resultPath 最终的文件地址
     * @param formatName 最终文件形式
     * @throws IOException
     */
    public static String mergeImage(String logoPath,String qrPath,String resultPath,String formatName)throws IOException {
        //  读取本地文件
//        File srcImgFile = new File(logoPath);
//        Image srcImg = ImageIO.read(srcImgFile);
        // 读取原图片信息(logo)
        URL logoUrl = new URL(logoPath);
        //将文件对象转化为图片对象
        Image srcImg = ImageIO.read(logoUrl);
        //获取图片的宽
        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);
        // 水印文件
        Image srcWaterMark = ImageIO.read(new File(qrPath));
        //获取水印图片的宽度
        int widthWaterMark= srcWaterMark.getWidth(null);
        //获取水印图片的高度
        int heightWaterMark = srcWaterMark.getHeight(null);
        //设置 alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
        //绘制水印图片  坐标为中间位置
        g.drawImage(srcWaterMark, (srcImgWidth - widthWaterMark) / 2,
                (srcImgHeight - heightWaterMark) / 2, widthWaterMark, heightWaterMark, null);
        // 水印文件结束
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(resultPath);
        ImageIO.write(bufImg, formatName, outImgStream);
        System.out.println("添加水印完成");
        outImgStream.flush();
        outImgStream.close();
        return resultPath;
    }


    public static void main(String[] args) throws IOException {
        String paths = "D:\\img\\yuan.png";
        System.out.println(paths);
        String text = "https://taceability.lpsrn.com.cn/prod-api/traceability/qrcode/getCodeValueByCode/?code=001001202208140120220815PD2022081600000000";
        createImg(text, 248, 248,
                paths, "001001202208140120220815PD2022081600000000", "png","D:\\img\\small.png");
    }
}

②接口调用

@GetMapping(value = "/createCode/{code}")
    public AjaxResult createQRCode(@PathVariable("code")String code){
      //请求地址
      String text = "https://rance.lpsrn.com.cn/prod-api/traceability/qrcode/getCodeValueByCode/?code="+code;
        AjaxResult ajaxResult = new AjaxResult();
        logger.info("【生成二维码接口】,请求参数:{}",code);
        try {
              String  diLogoPath = "https://n.oss-cn-beijing.aliyuncs.com/qrcode/20220824/8492a1e45f2745c384e0581317784790/logo.png";
              String smallPath = "https://n.oss-cn-beijing.aliyuncs.com/qrcode/20220824/16358df1a42c4191abdb6f2302e5a700/small.png";
              //图标在本地时使用
//            String  diLogoPath = "D:\\img\\logo.png";
//            String smallPath = "D:\\img\\small.png";
              String formatName = "png";
              String resultPath = QRCodeUtil.createImg(text,
                    1048, 1048, diLogoPath, code,formatName,smallPath);
              File file = new File(resultPath);
              if (file == null) {
                  return AjaxResult.error("文件内容为空");
              }
              ajaxResult.put("url", ossPath);
              ajaxResult.put("code",200);
        }catch(Exception e){
            logger.error("【生成二维码接口】异常信息:{}",e.getMessage());
            return  AjaxResult.error("系统异常");
        }
         logger.error("【生成二维码接口】响应信息:{}",JSON.toJSONString(ajaxResult));
          return ajaxResult;
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用 Java 的第三方库来生成二维码的海报。以下是一个使用 zxing 库生成海报二维码的源示例: ```java import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class PosterGenerator { public static void main(String[] args) { String qrCodeData = "https://www.example.com"; // 二维码内容 String filePath = "poster.png"; // 海报保存路径 String text = "Check out our website!"; // 海报文本内容 int size = 300; // 二维码尺寸 String fileType = "png"; // 海报文件类型 try { // 生成二维码 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, size, size); BufferedImage qrCodeImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); qrCodeImage.createGraphics(); Graphics2D graphics = (Graphics2D) qrCodeImage.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, size, size); graphics.setColor(Color.BLACK); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (bitMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } // 创建海报 BufferedImage posterImage = new BufferedImage(600, 800, BufferedImage.TYPE_INT_RGB); Graphics2D posterGraphics = (Graphics2D) posterImage.getGraphics(); posterGraphics.setColor(Color.WHITE); posterGraphics.fillRect(0, 0, 600, 800); posterGraphics.setColor(Color.BLACK); // 绘制二维码 int qrCodeX = 150; int qrCodeY = 150; posterGraphics.drawImage(qrCodeImage, qrCodeX, qrCodeY, size, size, null); // 绘制文本 Font font = new Font("Arial", Font.BOLD, 24); FontMetrics fontMetrics = posterGraphics.getFontMetrics(font); int textWidth = fontMetrics.stringWidth(text); int textX = (600 - textWidth) / 2; int textY = qrCodeY + size + 50; posterGraphics.setFont(font); posterGraphics.drawString(text, textX, textY); // 保存海报 ImageIO.write(posterImage, fileType, new File(filePath)); System.out.println("海报生成成功!"); } catch (WriterException | IOException e) { e.printStackTrace(); } } } ``` 这个示例使用了 zxing 库来生成二维码,并使用 Java 的 Graphics2D 类来创建海报并将二维码和文本绘制在海报上。您可以根据需要调整海报的尺寸、二维码的位置和大小、文本的内容和样式。请注意,您需要在项目中导入 zxing 库以及相关的依赖。 希望这个示例能对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值