使用java进行二维码的生成与读取使用到了谷歌的zxing.jar
第一步 导入,maven依赖或者下载指定jar包
com.google.zxing javase3.2.1
第二步 书写二维码生成器的工具类
import java.awt.Color;
import java.io.File;
import java.util.Hashtable;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRCodeFormat {
private int size;
private String encode;
private ErrorCorrectionLevel errorCorrectionLevel;
private double errorCorrectionLevelValue;
private Color foreGroundColor;
private Color backGroundColor;
private String imageFormat;
private int margin;
private Hashtable hints;
private File icon;
public static QRCodeFormat NEW() {
return new QRCodeFormat();
}
private QRCodeFormat() {
this.size = 256;
this.encode = "utf-8";
this.errorCorrectionLevel = ErrorCorrectionLevel.M;
this.errorCorrectionLevelValue = 0.15;
this.foreGroundColor = Color.BLACK;
this.backGroundColor = Color.WHITE;
this.imageFormat = "png";
this.margin = 0;
this.hints = new Hashtable();
}
public int getSize() {
return this.size;
}
public QRCodeFormat setSize(int size) {
this.size = size;
return this;
}
public String getEncode() {
return encode;
}
public QRCodeFormat setEncode(String encode) {
this.encode = encode;
return this;
}
public ErrorCorrectionLevel getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
public double getErrorCorrectionLevelValue() {
return errorCorrectionLevelValue;
}
public QRCodeFormat setErrorCorrectionLevel(char errorCorrectionLevel) {
switch (Character.toUpperCase(errorCorrectionLevel)) {
case 'L':
this.errorCorrectionLevel = ErrorCorrectionLevel.L;
this.errorCorrectionLevelValue = 0.07;
break;
case 'M':
this.errorCorrectionLevel = ErrorCorrectionLevel.M;
this.errorCorrectionLevelValue = 0.15;
break;
case 'Q':
this.errorCorrectionLevel = ErrorCorrectionLevel.Q;
this.errorCorrectionLevelValue = 0.25;
break;
case 'H':
this.errorCorrectionLevel = ErrorCorrectionLevel.H;
this.errorCorrectionLevelValue = 0.3;
break;
default:
this.errorCorrectionLevel = ErrorCorrectionLevel.M;
}
return this;
}
public Color getForeGroundColor() {
return foreGroundColor;
}
public QRCodeFormat setForeGroundColor(String foreGroundColor) {
try {
this.foreGroundColor = getColor(foreGroundColor);
}
catch (NumberFormatException e) {
this.foreGroundColor = Color.BLACK;
}
return this;
}
public QRCodeFormat setForeGroundColor(Color foreGroundColor) {
this.foreGroundColor = foreGroundColor;
return this;
}
public Color getBackGroundColor() {
return backGroundColor;
}
public QRCodeFormat setBackGroundColor(String backGroundColor) {
try {
this.backGroundColor = getColor(backGroundColor);
}
catch (NumberFormatException e) {
this.backGroundColor = Color.WHITE;
}
return this;
}
public QRCodeFormat setBackGroundColor(Color backGroundColor) {
this.backGroundColor = backGroundColor;
return this;
}
public String getImageFormat() {
return imageFormat.toUpperCase();
}
public QRCodeFormat setImageFormat(String imageFormat) {
this.imageFormat = imageFormat;
return this;
}
public int getMargin() {
return margin;
}
public QRCodeFormat setMargin(int margin) {
this.margin = margin;
return this;
}
public Hashtable getHints() {
hints.clear();
hints.put(EncodeHintType.ERROR_CORRECTION, getErrorCorrectionLevel());
hints.put(EncodeHintType.CHARACTER_SET, getEncode());
hints.put(EncodeHintType.MARGIN, getMargin());
return hints;
}
public File getIcon() {
return icon;
}
public QRCodeFormat setIcon(File icon) {
this.icon = icon;
return this;
}
public QRCodeFormat setIcon(String iconPath) {
return setIcon(new File(iconPath));
}
private Color getColor(String hexString) {
if (hexString.charAt(0) == '#') {
return new Color(Long.decode(hexString).intValue());
} else {
return new Color(Long.decode("0xFF" + hexString).intValue());
}
}
}
第三步 使用生成器对象按照指定格式进行生成读取二维码
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
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.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
public final class QRCode {
private QRCodeFormat format = null;
private BufferedImage qrcodeImage = null;
private File qrcodeFile = null;
public BufferedImage getQrcodeImage() {
return qrcodeImage;
}
public File getQrcodeFile() {
return qrcodeFile;
}
private QRCode() {
}
public static QRCode NEW(final String content) {
return NEW(content, QRCodeFormat.NEW());
}
public static QRCode NEW(final String content, QRCodeFormat format) {
QRCode qrcode = new QRCode();
qrcode.format = format;
qrcode.qrcodeImage = toQRCode(content, format);
return qrcode;
}
public QRCode toFile(String f) {
return toFile(new File(f), this.format.getIcon());
}
public QRCode toFile(File qrcodeFile) {
return toFile(qrcodeFile, this.format.getIcon());
}
public QRCode toFile(String qrcodeFile, String appendFile) {
if (null == appendFile || appendFile.length() == 0) {
return toFile(new File(qrcodeFile));
}
return toFile(new File(qrcodeFile), new File(appendFile));
}
public QRCode toFile(File qrcodeFile, File appendFile) {
try {
if (!qrcodeFile.exists()) {
qrcodeFile.getParentFile().mkdirs();
qrcodeFile.createNewFile();
}
if (null != appendFile && appendFile.isFile() && appendFile.length() != 0) {
appendImage(ImageIO.read(appendFile));
}
if (!ImageIO.write(this.qrcodeImage, getSuffixName(qrcodeFile), qrcodeFile)) {
throw new RuntimeException("Unexpected error writing image");
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
this.qrcodeFile = qrcodeFile;
return this;
}
private void appendImage(BufferedImage appendImage) {
appendImage(this.qrcodeImage, appendImage, this.format);
}
private static void appendImage(BufferedImage qrcodeImage, BufferedImage appendImage, QRCodeFormat format) {
int baseWidth = qrcodeImage.getWidth();
int baseHeight = qrcodeImage.getHeight();
// 计算 icon 的最大边长
// 公式为 二维码面积*错误修正等级*0.4 的开方
int maxWidth = (int) Math.sqrt(baseWidth * baseHeight * format.getErrorCorrectionLevelValue() * 0.4);
int maxHeight = maxWidth;
// 获取 icon 的实际边长
int roundRectWidth = (maxWidth < appendImage.getWidth()) ? maxWidth : appendImage.getWidth();
int roundRectHeight = (maxHeight < appendImage.getHeight()) ? maxHeight : appendImage.getHeight();
BufferedImage roundRect = new BufferedImage(roundRectWidth, roundRectHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = roundRect.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fillRoundRect(0, 0, roundRectWidth, roundRectHeight, 27, 27);
g2.setComposite(AlphaComposite.SrcAtop);
g2.drawImage(appendImage, 0, 0, roundRectWidth, roundRectHeight, null);
g2.dispose();
Graphics gc = qrcodeImage.getGraphics();
gc.setColor(format.getBackGroundColor());
gc.drawImage(roundRect, (baseWidth - roundRectWidth) / 2, (baseHeight - roundRectHeight) / 2, null);
gc.dispose();
}
public static BufferedImage toQRCode(String content) {
return toQRCode(content, null);
}
public static BufferedImage toQRCode(String content, QRCodeFormat format) {
if (format == null) {
format = QRCodeFormat.NEW();
}
content = new String(content.getBytes(Charset.forName(format.getEncode())));
BitMatrix matrix = null;
try {
matrix = new QRCodeWriter().encode(content,
BarcodeFormat.QR_CODE,
format.getSize(),
format.getSize(),
format.getHints());
}
catch (WriterException e) {
throw new RuntimeException(e);
}
int width = matrix.getWidth();
int height = matrix.getHeight();
int fgColor = format.getForeGroundColor().getRGB();
int bgColor = format.getBackGroundColor().getRGB();
BufferedImage image = new BufferedImage(width, height, ColorSpace.TYPE_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? fgColor : bgColor);
}
}
File appendFile = format.getIcon();
if (null != appendFile && appendFile.isFile() && appendFile.length() != 0) {
BufferedImage appendImage = null;
try {
appendImage = ImageIO.read(appendFile);
}
catch (IOException e) {
throw new RuntimeException(e);
}
appendImage(image, appendImage, format);
}
return image;
}
public static String from(String qrcodeFile) {
if (qrcodeFile.startsWith("http://") || qrcodeFile.startsWith("https://")) {
try {
return from(new URL(qrcodeFile));
}
catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else {
return from(new File(qrcodeFile));
}
}
public static String from(File qrcodeFile) {
try {
BufferedImage image = ImageIO.read(qrcodeFile);
return from(image);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String from(URL qrcodeUrl) {
try {
BufferedImage image = ImageIO.read(qrcodeUrl);
return from(image);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String from(BufferedImage qrcodeImage) {
LuminanceSource source = new BufferedImageLuminanceSource(qrcodeImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
String content = null;
try {
Result result = new QRCodeReader().decode(bitmap);
content = result.getText();
}
catch (NotFoundException e) {
throw new RuntimeException(e);
}
catch (ChecksumException e) {
throw new RuntimeException(e);
}
catch (FormatException e) {
throw new RuntimeException(e);
}
return content;
}
private String getSuffixName(File file) {
String path = file.getAbsolutePath();
if (null == path) {
return this.format.getImageFormat();
}
int pos = path.lastIndexOf('.');
if (-1 == pos) {
return this.format.getImageFormat();
}
return path.substring(pos + 1).toUpperCase();
}
public static void main(String[] args) throws IOException {
String str="https://blog.csdn.net/jiandanyou/article/details/109751418";
QRCode.NEW(str).toFile("d:\2.jpg");//使用指定字符串生成二维码
System.out.println(QRCode.from("d:/2.jpg"));//读取解析指定二维码
}
}
第四步 使用
工具类中的方法使用的静态方法,可以直接使用QRCode.方法进行执行
生成二维码方法
QRCode.NEW(str).toFile(url);
str:二维码中包含的字符串(如果包含地址前缀添加http或https 否则不能自动跳转 会解析地址字符串)
url:二维码图片生成位置
QRCode.from(url);
url:要解析二维码图片位置
到此这篇关于java使用jar包生成二维码的示例代码的文章就介绍到这了,更多相关java jar包生成二维码内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!



