Java后端二维码

在pom.xml导入zxing包

<!-- 生成二维码 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.1</version>
        </dependency>

QRCodeUtils 二维码 工具类


import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HaleyHa
 * @date 2021/12/10 19:18
 * @description 二维码 工具类
 *
 * **/
@Component
public class QRCodeUtils {
    //日志
//    private static final Logger logger = LoggerFactory.getLogger(QRCodeUtils.class);

    //二维码颜色
    private static final int BLACK = 0xFF000000;
    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;
    //二维码宽
    private static final int width = 200;
    //二维码高
    private static final int height = 200;
    //二维码生成格式
    private static final String imageType = "png";

    /**
     * 生成二维码
     * @param text    二维码内容
     */
    public static String zxingCodeCreate(String text) throws Exception{
        HashMap map = new HashMap();
        //EncodeHintType枚举类 纠错程度(使得其精度增加)
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //字符编码
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        //二维码边距
        map.put(EncodeHintType.MARGIN,1);

        //生成二维码
        BitMatrix encode = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE,width,height);
        int codeWidth = encode.getWidth();
        int codeHeight = encode.getHeight();
        BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);// 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);
                }
        }
        return imageToString(image);
    }

    //把image对象转换成Base64方法
    public static String imageToString(BufferedImage image) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image,imageType,os);
        return Base64.encodeBase64String(os.toByteArray());
    }

}

控制类QRCodeController


import com.coupon.dto.Result;
import com.coupon.util.QRCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author HaleyHa
 * @date 2021/12/11 16:26
 * @description: 二维码管理模块
 */
//@SuppressWarnings("all")
@RestController
@RequestMapping("/qrcode")
@Api(tags = "二维码管理")
public class QRCodeController {

    @Autowired
    QRCodeUtils qrCodeUtils;

//    @ResponseBody
    @ApiOperation(value = "生成二维码")
    @PostMapping("/create")
    public String createQRCode(@RequestParam(value = "text")String text) throws Exception {
        return qrCodeUtils.zxingCodeCreate(text);
    }

}

前端页面实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单文件上传</title>
</head>
<style>
    image[src=""],img:not([src]){
        opacity: 0;
    }
</style>
<body>
    <input type="text" id="text" placeholder="请输入">
    <img src="" id="preview_photo" width="200px" height="200px">
    <ul>
        <li><input type="button" id="normal" value="生成普通二维码" onclick="upload('normal')"></li>
    </ul>
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    function upload(flag) {
        var formData = new FormData();
        formData.append('text',document.getElementById('text').value);
        // formData.append('flag',flag);
        $.ajax({
            url:"http://localhost:8001/qrcode/create",
            type:"post",
            data:formData,
            contentType:false,
            processData:false,
            success:function(data) {
                $("#preview_photo").attr("src","data:image/png;base64,"+data);
            },
            error:function(data){

                alert("上传失败")
            }
        })
    }
</script>
</html>

参考资料:
b站视频:https://www.bilibili.com/video/BV1ez4y1S7h7?from=search&seid=13314849704773297464&spm_id_from=333.337.0.0
csdn资料:https://blog.csdn.net/weixin_42290280/article/details/90731220

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成二维码Java后端代码可以使用zxing库来实现。首先,你需要在你的项目中引入zxing库的依赖。然后,你可以使用以下代码来生成二维码: ```java import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class QRCodeGenerator { public static void generateQRCode(String text, int width, int height, String filePath) { try { BitMatrix matrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height); 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, matrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB()); } } ImageIO.write(image, "png", new File(filePath)); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String text = "https://example.com"; // 二维码中的内容 int width = 200; // 二维码的宽度 int height = 200; // 二维码的高度 String filePath = "qrcode.png"; // 保存二维码的文件路径 generateQRCode(text, width, height, filePath); } } ``` 上述代码使用zxing库中的`MultiFormatWriter`和`BarcodeFormat.QR_CODE`来生成二维码。`generateQRCode`方法接收四个参数:二维码中的文本内容、二维码的宽度、二维码的高度和保存二维码的文件路径。通过循环遍历位矩阵的每个点,将黑色像素点设置为Color.BLACK,将白色像素点设置为Color.WHITE,最后使用`ImageIO.write`方法将生成二维码保存到文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值