1.引入架包
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.1</version> </dependency>
2.Java实体类中增加字段
@ApiModelProperty(value = "二维码") private String qrCode;
3.MySQL表中增加字段,类型为blob
alter table `tableName` add column `qr_code` blob null comment '二维码' ;
4.生成工具类
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import java.util.Hashtable; public class QRCodeUtil { public static String generateQRCodeToBase64(String text, int width, int height) throws WriterException, IOException { com.google.zxing.Writer writer = new QRCodeWriter(); Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height, hints); BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); baos.flush(); byte[] imageBytes = baos.toByteArray(); baos.close(); return Base64.getEncoder().encodeToString(imageBytes); } // 将Base64字符串解码为二维码图片的方法(可选) public static BufferedImage decodeBase64ToQRCodeImage(String base64String) throws IOException { byte[] imageBytes = Base64.getDecoder().decode(base64String); return ImageIO.read(new ByteArrayInputStream(imageBytes)); } /** * https://blog.csdn.net/qq_60542647/article/details/138083115 二维码转base64 * https://www.lddgo.net/convert/base64-to-image base64 在线Base64转图片 * @param args */ public static void main(String[] args) { try { String base64 = generateQRCodeToBase64("www.baidu.com", 200, 200); System.out.println(base64); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
标签:google,Java,java,base64,zxing,MySQL,import,com From: https://www.cnblogs.com/Jack-zhao/p/18214503