1.所需Jar包 core-3.3.0.jar, javase-3.3.0.jar
2.二维码的生成
/**
* 生成二维码
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) throws WriterException, IOException {
MultiFormatWriter writer=new MultiFormatWriter();
String contents="http://szcet.cn/";
int w=400;
int h=400;
HashMap<EncodeHintType,Object> hits=new HashMap<>();
hits.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix=writer.encode(contents, BarcodeFormat.QR_CODE, w, h,hits);
//创建图片
BufferedImage qr=new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
for(int x=0;x<w;x++){
for(int y=0;y<h;y++){
if(bitMatrix.get(x, y)){
qr.setRGB(x, y, 0xFF0000);
}else{
qr.setRGB(x, y, 0xffffff);
}
}
}
//读取logo
BufferedImage logimImage=ImageIO.read(new File("d:/cntlogo.png"));
int logoh=50,logow=50;
Image logoUse=logimImage.getScaledInstance(logow, logoh, Image.SCALE_FAST);
//2绘制logo
Graphics g1=qr.getGraphics();
int logoX=(w-logow)/2;
int logoY=(h-logoh)/2;
g1.drawImage(logoUse,logoX,logoY,null);
ImageIO.write(qr,"png",new File("d:/2.png"));
//MatrixToImageWriter.writeToPath(bitMatrix, "png", new File("d:/1.png").toPath());
}
}
3.二维码的读取
public class Test1 {
/**
* 二维码的读取
* @param args
*/
public static void main(String[] args) throws Exception{
//1.读取图片
BufferedImage img=ImageIO.read(new File("D:/2.png"));
//2.转换为亮度数据源
LuminanceSource luminanceSource=new BufferedImageLuminanceSource(img);
//3.使用转换器把亮度数据源转换为二进制位数据
Binarizer binarizer =new HybridBinarizer(luminanceSource);
//4.二进制位数据转换位二进制位图
BinaryBitmap binaryBitmap=new BinaryBitmap(binarizer);
//5读取内容
MultiFormatReader formatReader=new MultiFormatReader();
HashMap<DecodeHintType, Object> hints=new HashMap<>();
//hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result=formatReader.decode(binaryBitmap,hints);
String contents=result.getText();
System.out.println(contents);
}
}