如何实现二维码的编解码?

112 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

  1. 依赖
<!--生成二维码-->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.0</version>
</dependency>
  1. 代码
public class QRCodeTest {   
 	static String file = "G:/code.png";   
 	static String utf8 = "utf8";    
  	static int width=300;    
  	static int height=300;    
  	static String format="png";    
  	static String content="哈哈哈";    
  	static class EncodeTest {        
  		public static void main(String[] args) throws Exception {  
  		          	HashMap<EncodeHintType, Object> hints=new HashMap<>(1);   
  		            hints.put(EncodeHintType.CHARACTER_SET, utf8);            
  		            BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);            
  		            Path path = new File(file).toPath();            
  		            MatrixToImageWriter.writeToPath(bitMatrix, format, path);       
  		}    
  }    
  static class DecodeTest {       
  	public static void main(String[] args) throws Exception {            
  		              MultiFormatReader reader = new MultiFormatReader();           
  		              BufferedImage bufferedImage = ImageIO.read(new File(file));            
  		              BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));            
  		              Result result = reader.decode(binaryBitmap);            
  		              System.out.println(result.getText());        
  	}   
  }
  }