package com;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
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;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class CreateQRCode {
@Test
public void creatQRCode() throws IOException{
int width =300;
int height= 300;
String format ="png";
String contents="测试1111111111";
HashMap hints=new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try {
BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,hints);
File file = new File("d:/codes");
if(!file.exists()){
file.mkdir();
}
MatrixToImageWriter.writeToPath(matrix, format, new File(file,"test.png").toPath());
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void readQRCode() throws IOException, NotFoundException{
MultiFormatReader multiFormatReader = new MultiFormatReader();
File file = new File("d:/codes/test1.png");
BufferedImage img = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(img)));
HashMap hints=new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
Result decode = multiFormatReader.decode(binaryBitmap,hints);
System.err.println(decode.getText());
}
}package com;
import java.awt.image.BufferedIma