preface
Two-dimensional code can be seen everywhere in our life. As a programmer, we have not thought about generating a two-dimensional code to play with it. In fact, it is very simple, we directly use the com.Google.zxing provided by Google.
Two-dimensional code rendering
The QR code is generated on the PC
The generated QR code is divided into two parts
- Black and white QR code
- The LOGO of station B in the middle
The following code shows how to merge the two images.
Wechat scan
Not only can you scan text, you can also scan jump links, you can also scan to generate pictures. Just fill in the input fields with different information.
For example, we enter https://www.baidu.com/ and scan the QR code to jump directly to baidu’s website
Such as we enter the address https://img-blog.csdnimg.cn/20200629104712300.jpg, will be displayed after scanning the corresponding pictures.
Code implementation
Maven configuration
<! Zxing </groupId> <artifactId>core</artifactId> <version>3.3. 0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3. 0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
Copy the code
controller
@RestController
@RequestMapping("/qrCode")
public class QRCodeGeneratorController {
@GetMapping("/generator")
public void encodeQrCode(String codeContent, HttpServletResponse response) {
// Embed the image path of qr code
String imgPath = "C:\\Users\\hp\\Desktop\\bilibili.jpg";
try {
QRCodeUtil.encode(codeContent, imgPath, true, response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); }}}Copy the code
Core util class
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
// Size of the qr code
private static final int QRCODE_SIZE = 300;
/ / the LOGO width
private static final int WIDTH = 100;
/ / the LOGO height
private static final int HEIGHT = 100;
/** * The incoming information from the front end, Code into a TWO-DIMENSIONAL code * @param Content * @Param imgPath * @Param needCompress * @param outputStream * @throws Exception */
public static void encode(String content, String imgPath, boolean needCompress, OutputStream outputStream) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
ImageIO.write(image, "png", outputStream);
}
/** * Generate the core code of the QR code * @param Content * @Param imgPath * @Param needCompress * @return * @throws Exception */
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
HashMap hints = new HashMap(16);
// Specify the degree of error correction to use, for example in a QR code.
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// Specify the character encoding
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
// Specifies the margin, in pixels, to use when generating the bar code.
hints.put(EncodeHintType.MARGIN, 1);
// Generate a two-dimensional bit matrix
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
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++) {
// true is black, false is white
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); }}if (imgPath == null || "".equals(imgPath)) {
return image;
}
// Insert a LOGO image
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/** * Insert the bilibili LOGO * @param source * @param imgPath * @param needCompress * @throws Exception */
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
if(! file.exists()) { System.err.println("" + imgPath + "This file does not exist!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
/ / compression LOGO
if (needCompress) {
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
// Create a scaled version of this image.
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = tag.getGraphics();
// Draw the reduced figure
graphics.drawImage(image, 0.0, null);
graphics.dispose();
src = image;
}
/ / insert the LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6.6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
* @param path * @return * @throws Exception */
public static String decode(String path) throws Exception {
File file = new File(path);
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
returnresultStr; }}Copy the code
html
<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0"/> <title> </title> <styletype="text/css">
textarea {
font-size: 16px;
width: 300px;
height: 100px;
}
.hint {
color: red;
display: none;
}
.qrCodeDiv {
width: 200px;
height: 200px;
border: 2px solid sandybrown;
}
.qrCodeDiv img {
max-height: 100%;
max-width: 100%;
}
</style>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("button").click(function () {
var codeContent = $("textarea").val();
console.log(codeContent);
/** * if the output content is empty, it will prompt, otherwise change the address of img to generate a qr code */
if (codeContent.trim() == "") {$(".hint").text("Two-dimensional code content cannot be empty").fadeIn(500);
} else{$(".hint").text("").fadeOut(500);
/**coco is the application name, qrCode is the background access path, and codeContent is the parameter received by the background control layer */
$("#codeImg").attr("src"."/qrCode/generator? codeContent="+ codeContent); }}); }); </script> </head> <body> <textarea placeholder="Qr code content..."></textarea><br> <button> generate qr code </button> <span class="hint"></span> <! -- Qr code display song, like verification code, directly use the IMG tag request can be --> <! QrCode is the background access path, and codeContent is the parameter carried by the GET request with a value of"Thank you"-- > <! <img SRC = <img SRC ="/coco/qrCode? CodeContent = thank you" id="codeImg">, coco is the application name --> <div class="qrCodeDiv">
<img src="" th:src="@ {/ qrCode (codeContent = thank you)}" id="codeImg">
</div>
</body>
</html>
Copy the code
Code download address
Link: pan.baidu.com/s/1Qt1ttXGj…
Extraction code: DUkf
Don’t forget to replace the LOGO picture address in controller
// Embed the image path of qr code
String imgPath = "C:\\Users\\hp\\Desktop\\bilibili.jpg";
Copy the code