Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate QR Code in java

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Java how to achieve the generation of two-dimensional code, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need this can learn, I hope you can gain something.

If it's a maven project, add dependencies to the project com.google.zxing javase 3.3.0package com.aigyun.config;import com.aigyun.constant.StringUtils;import com.aigyun.entity.DeviceUavInfo;import com.alibaba.fastjson.JSONObject;import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import com.swetake.util.Qrcode;import lombok.extern.slf4j.Slf4j;import javax.imageio.ImageIO;import java.awt.*; import java.awt.image.BufferedImage;import java.io.*; import java.nio.file.FileSystems;import java.nio.file.Path;import java.time.LocalDateTime;import java.util.HashMap;import java.util.Map;import java.util.Objects;import java.util.UUID;public class QCodeUtil { private static final int QRCOLOR = 0xFF 00000; //default is black private static final int BGWHITE = 0xFFFFFF; //background color //Used to set QR code parameters private static Map hints = new HashMap() { private static final long serialVersionUID = 1L; { put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Sets the error correction level of QR code (H is the highest level) put(EncodeHintType.CHARACTER_SET, "utf-8");//Set encoding mode put(EncodeHintType.MARGIN, 0); } }; /** * Java draws two-dimensional codes that contain only content * * @param content * @param imgPath */ public static void getQrCodeImg(String content, String imgPath) { int width = 300; int height = 300; Qrcode qrcode = new Qrcode(); qrcode.setQrcodeErrorCorrect('M '); //Set error correction level (levels: L(7%) M(15%) Q(25%) H(30%)) qrcode.setQrcodeEncodeMode ('B '); //Set encoding mode qrcode.setQrcodeVersion(7); //Set QR code version (1-40 versions) // 1. Set image size (Buffered Image.TYPE_INT_RGB: Draw QR code with three primary colors) BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gs = img.createGraphics(); //Create brush gs.setBackground(Color.WHITE); //Set Background to White gs.clearRect(0, 0, width, height); //Set a rectangle (four parameters are: x-coordinate, y-coordinate, image width, image height) gs.setColor(Color.BLACK); //Set the color of the QR code image byte[] bt = null; //Convert contents to byte array try { bt = content.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } int py = 4; //offset boolean[][] code = qrcode.calQrcode(bt); //Start preparing for drawing for (int i = 0; i

< code.length; i++) { for (int j = 0; j < code[i].length; j++) { if (code[j][i]) { // 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的)); gs.fillRect(j * 6 + py, i * 6 + py, 6, 6); } } } // 画图 try { ImageIO.write(img, "png", new File(imgPath)); System.out.println("OK!"); } catch (IOException e) { System.out.println("二维码异常。。。。。"); e.printStackTrace(); } } public static String decode(String filepath) { try { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath)); LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); HashMap decodeHints = new HashMap(); decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); Result result = new MultiFormatReader().decode(bitmap, decodeHints); return result.getText(); } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * zxing生成带logo的二维码 * * @param logoFile * @param codeFile * @param qrUrl * @param note */ public static boolean drawLogoQRCode(final File logoFile, File codeFile, final String qrUrl, final String note, final int width, final int height) { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); BitMatrix bm = null; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); ; try { // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数 bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, width, height, hints); } catch (WriterException we) { we.printStackTrace(); return false; } // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE); } } //绘制图片 Graphics2D g = image.createGraphics(); try { BufferedImage logo = ImageIO.read(logoFile); g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null); g.dispose(); logo.flush(); } catch (IOException e) { e.printStackTrace(); return false; } // 自定义文本描述 if (StringUtils.isNotEmpty(note)) { // 新的图片,把带logo的二维码下面加上文字 BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D outg = outImage.createGraphics(); // 画二维码到新的面板 outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); // 画文字到新的面板 outg.setColor(Color.BLACK); outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号 int strWidth = outg.getFontMetrics().stringWidth(note); if (strWidth >

399) { //If the length is too long, cut off the front part //If the length is too long, it will be changed. String note1 = note.substring(0, note.length() / 2); String note2 = note.substring(note.length() / 2, note.length()); int strWidth2 = outg.getFontMetrics().stringWidth(note1); int strWidth3 = outg.getFontMetrics().stringWidth(note2); outg.drawString(note1, 200 - strWidth2 / 2, height + (outImage.getHeight() - height) / 2 + 12); BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D outg2 = outImage2.createGraphics(); outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null); outg2.setColor(Color.BLACK); outg2.setFont(new Font("Song", Font.BOLD, 30)); //font, font, font size outg2.drawString(note2, 200 - strWidth3 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5); outg2.dispose(); outImage2.flush(); outImage = outImage2; } else { outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); //draw text } outg.dispose(); outImage.flush(); image = outImage; } image.flush(); try { ImageIO.write(image, "png", codeFile); // TODO } catch (IOException e) { e.printStackTrace(); return false; } return true; } public static void main(String[] args) {// JSONObject jsonObject = new JSONObject();// jsonObject.put("reg_id", 12123);// getQrCodeImg(jsonObject.toJSONString(), "f:/qrcode/test1.jpg");// //encode(jsonObject.toJSONString(), "f:/qrcode/test.jpg");// File logoFile = new File("f:/qrcode/512x512bb.jpg");// File codeFile = new File("f:/qrcode/test.png");// drawLogoQRCode(logoFile, codeFile, jsonObject.toJSONString(),"Scan to view configuration parameters");/// String content = decode("f:/qrcode/test.jpg");// System.out.println(content); System.out.println(UUID.randomUUID().toString()); Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report