1,添加jar
<!--二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.1.0</version>
</dependency>
2,
package com.taotao.cms.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
public class erweima {
public static void main(String[] args)throws Exception {
System.out.println("123");
String text="WANGZHEWUDIZHONGHENG";
int width=300;
int height =300;
String format="png";
Hashtable hints= new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
BitMatrix bitMatrix =null;
try{
bitMatrix =new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE,width,height,hints);
}catch (WriterException e){
e.printStackTrace();
}
//直接写入文件
File outputFile =new File("d:/new.png");
MatrixToImageWriter.writeToFile(bitMatrix,format,outputFile);
//通过流写入文件buxuyao flush
OutputStream os1=new FileOutputStream("d:/new2.png");
MatrixToImageWriter.writeToStream(bitMatrix,format,os1);
BufferedImage image =MatrixToImageWriter.toBufferedImage(bitMatrix);
ByteArrayOutputStream os=new ByteArrayOutputStream();//新建流
ImageIO.write(image,format,os);//利用ImageIo类提供的write方法,将bi以png图片数据模式写入流
byte b[] =os.toByteArray();//从流中获取数据数组
String str= new BASE64Encoder().encode(b);
System.out.println(str);
}
}