用zxing生成和解析二维码
Posted 东山磐石西山流云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用zxing生成和解析二维码相关的知识,希望对你有一定的参考价值。
package test; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.junit.Test; import com.google.zxing.BarcodeFormat; import com.google.zxing.Binarizer; import com.google.zxing.BinaryBitmap; import com.google.zxing.EncodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.WriterException; 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; public class Erweima { /** * 生成二维码 */ @Test public void create(){ try { String content = "https://www.baidu.com/";//一般放url,比如微信,扫描后直接跳转到指定url链接 String path = "E:/";//生成的二维码指定一个地方存放 MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints); File file1 = new File(path,"love.jpg");//生成的二维码名字love.jpg,可以自己指定叫什么名字,以图片的格式 MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 解析二维码 */ @Test public void get(){ try { MultiFormatReader formatReader = new MultiFormatReader(); String filePath = "E:/love.jpg"; File file = new File(filePath); BufferedImage image = ImageIO.read(file);; LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); Result result = formatReader.decode(binaryBitmap,hints); System.out.println("result = "+ result.toString()); System.out.println("resultFormat = "+ result.getBarcodeFormat()); System.out.println("resultText = "+ result.getText()); } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
所需jar包:https://files.cnblogs.com/files/fpc-syq/zxing%E7%94%9F%E6%88%90%E4%BA%8C%E7%BB%B4%E7%A0%81%EF%BC%88jdk1.6%E4%B8%8B%E4%BA%B2%E6%B5%8B%E5%8F%AF%E7%94%A8%EF%BC%89.zip
以上是关于用zxing生成和解析二维码的主要内容,如果未能解决你的问题,请参考以下文章