第一种:下载jar包。
package ErWeiMa;
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 ErWeiMa {
public static void main(String[] args) throws WriterException, IOException {
int width = 300;
int height = 300;
String format = "png";
String content = "https://www.taobao.com/";
//定义二维码的参数
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
Path file = new File("D:/img.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
}
}
第二种:下载jar包
package ErWeiMa;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;
public static void main(String[] args) throws IOException {
Qrcode x = new Qrcode();
x.setQrcodeErrorCorrect('M');//纠错等级
x.setQrcodeEncodeMode('B');//N代表数字,A代表a-Z,B代表其他字符
x.setQrcodeVersion(7);//版本
String qrData = "https://www.baidu.com/";
int width = 67+12*(7-1);
int height = 67+12*(7-1);
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.yellow);
gs.setColor(Color.BLUE);
gs.clearRect(0, 0, width, height);
byte[] d = qrData.getBytes("utf-8");
if(d.length>=0 && d.length<120){
boolean[][] s= x.calQrcode(d);
for(int i =0;i<s.length;i++){
for(int j = 0;j<s.length;j++){
if(s[j][i]){
gs.fillRect(j*3+2, i*3+2, 3, 3);
}
}
}
}
gs.dispose();
bufferedImage.flush();
ImageIO.write(bufferedImage, "png", new File("D:/qrcode.png"));
}
}
第三种:(解析二维码)
package ErWeiMa;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import jp.sourceforge.qrcode.QRCodeDecoder;
public class ErWeiMaByQrCodeJieXi {
public static void main(String[] args) throws IOException {
File file = new File("D:/qrcode.png");
BufferedImage bufferedImage = ImageIO.read(file);
QRCodeDecoder codeDecoder = new QRCodeDecoder();
String result = new String(codeDecoder.decode(new MYQRCodeImage(bufferedImage)),"utf-8");
System.out.println(result);
}
}