二维码的生成与解析
1 package org.schiller; 2 3 import com.google.zxing.*; 4 import com.google.zxing.client.j2se.BufferedImageLuminanceSource; 5 import com.google.zxing.client.j2se.MatrixToImageWriter; 6 import com.google.zxing.common.BitMatrix; 7 import com.google.zxing.common.HybridBinarizer; 8 import org.junit.Test; 9 10 import javax.imageio.ImageIO; 11 import java.awt.image.BufferedImage; 12 import java.io.File; 13 import java.io.IOException; 14 import java.util.HashMap; 15 import java.util.Map; 16 17 public class AppTest { 18 @Test 19 public void save() throws IOException { //生成二维码 20 21 int width = 400; // 图像宽度 22 int height = 400; // 图像高度 23 String format = "png"; // 图像类型 24 String content = "org.schiller"; //二维码中的字符串内容 25 Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); 26 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 27 BitMatrix bitMatrix = null; // 生成矩阵 28 try { 29 bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); 30 } catch (WriterException e) { 31 e.printStackTrace(); 32 } 33 MatrixToImageWriter.writeToFile(bitMatrix, format, new File("D:/test.png"));// 输出图像 34 System.out.println("图片文件已经生成"); 35 } 36 37 @Test 38 public void show() { //解析二维码 39 String filePath = "D:/test.png"; 40 BufferedImage image; 41 try { 42 image = ImageIO.read(new File(filePath)); 43 LuminanceSource source = new BufferedImageLuminanceSource(image); 44 Binarizer binarizer = new HybridBinarizer(source); 45 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); 46 Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>(); 47 hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); 48 Result result = new MultiFormatReader().decode(binaryBitmap, hints); // 对图像进行解码 49 System.out.println("图片中内容:" + result.getText()); 50 System.out.println("图片中格式:"); 51 System.out.println("条码格式:" + result.getBarcodeFormat()); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } catch (NotFoundException e) { 55 e.printStackTrace(); 56 } 57 } 58 59 }
【说明】
引入俩jar包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
参考地址 http://blog.csdn.net/javaweiming/article/details/72844581