import Java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class TestZXing { public static void main(String[] args) { int width=300; int height=300; String format="png"; String contents="www.linuxidc.com"; HashMap map=new HashMap(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M); map.put(EncodeHintType.MARGIN, 0); try { BitMatrix bm = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height); Path file=new File("D:/img.png").toPath(); MatrixToImageWriter.writeToPath(bm, format, file); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
通过上面的代码则会生成一个内容链接为的二维码
对这个二维码的解析的代码如下
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import javax.imageio.ImageIO; import com.google.zxing.BinaryBitmap; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; public class TestRead { public static void main(String[] args) { try { MultiFormatReader reader=new MultiFormatReader();//需要详细了解MultiFormatReader的小伙伴可以点我一下官方去看文档 File f=new File("D:/img.png"); BufferedImage image=ImageIO.read(f); BinaryBitmap bb=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))); HashMap map =new HashMap(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); Result result = reader.decode(bb,map); System.out.println("解析结果:"+result.toString()); System.out.println("二维码格式类型:"+result.getBarcodeFormat()); System.out.println("二维码文本内容:"+result.getText()); } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
执行的结果如下
1 2 3
解析结果: 二维码格式类型:QR_CODE 二维码文本内容:
具体的jar包小伙伴可以自行下载
可以到Linux公社资源站下载:
------------------------------------------分割线------------------------------------------
具体下载目录在 /2017年资料/7月/25日/关于Java的二维码的生成与解析/
------------------------------------------分割线------------------------------------------