Overview
ZXing is an open source Java class library for parsing 1D/2D barcodes in multiple formats. The goal is to be able to decode 1D barcodes of QR encoding, Data Matrix, and UPC. It provides clients on multiple platforms including: J2ME, J2SE and Android.
Practical
This example demonstrates how to use ZXing to generate and parse QR code images in a non-android Java project.
Installation
The maven project only needs to introduce dependencies:
com.google.zxing core 3.3.0 com.google.zxing javase 3.3.0
Generate QR code images
ZXing has the following steps to generate QR code images:
1.com.google.zxing.MultiFormatWriter generates an image 2D matrix based on the content and image encoding parameters.
2. com.google.zxing.client.j2se.MatrixToImageWriter generates image files or image cache BufferedImage based on the image matrix.
public void encode(String content, String filepath) throws WriterException, IOException { int width = 100; int height = 100; MapencodeHints = new HashMap (); encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, encodeHints); Path path = FileSystems.getDefault().getPath(filepath); MatrixToImageWriter.writeToPath(bitMatrix, "png", path); }
Parsing QR code images
ZXing has the following steps to parse QR code images:
1. Use javax.imageio.ImageIO to read Image files are stored as a java.awt.image.BufferedImage object.
2. Convert java.awt.image.BufferedImage into a com.google.zxing.BinaryBitmap object that ZXing can recognize.
3.com.google.zxing.MultiFormatReader Parses com.google.zxing.BinaryBitmap based on image decoding parameters.
public String decode(String filepath) throws IOException, NotFoundException { BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath)); LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(binarizer); HashMapdecodeHints = new HashMap (); decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); Result result = new MultiFormatReader().decode(bitmap, decodeHints); return result.getText(); }
The following is an example of a generated QR code image:
The above is the entire article The content, I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.
For more related articles on small examples of ZXing generating and parsing QR code images in Java, please pay attention to the PHP Chinese website!