文章目录
二维码的简介:
java实现二维码的生成和解析:QRCode、zxing 两种方式
QRCode是日本人开发的ZXing是google开发的
第一种:QRCode.jar,使用QRCode生成二维码
生成二维码代码
import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class QRCodeUtil {
/**
*加密: 文字信息 ->二维码.png
* @param content 文字信息
* @param imgPath 二维码路径
* @param imgType 二维码类型:png
* @param size 二维码尺寸
* @throws Exception
*/
public void encoderQRCode(String content,String imgPath,String imgType,int size) throws Exception{
//BufferedImage :内存中的一张图片
BufferedImage bufImg = qRcodeCommon(content,imgType,size);
File file = new File(imgPath);// "src/二维码.png" --> 二维码.png
//生成图片
ImageIO.write(bufImg, imgType, file);
}
/**
*产生一个二维码的BufferedImage
* @param content 二维码隐藏信息
* @param imgType 图片格式
* @param size 图片大小
* @return
*/
private BufferedImage qRcodeCommon(String content, String imgType, int size) throws Exception {
BufferedImage bufImg =null;
//Qrcode对象:字符串->boolean[][]
Qrcode qrCodeHandler = new Qrcode();
//设置二维码的排错率:7% L<M<Q<H30% :排错率越高,可存储的信息越少;但是对二维码清晰对要求越小
qrCodeHandler.setQrcodeErrorCorrect('M');
//可存放的信息类型:N:数字、 A:数字+A-Z B:所有
qrCodeHandler.setQrcodeEncodeMode('B');
//尺寸:取值范围:1-40
qrCodeHandler.setQrcodeVersion(size);
//"Hello world" -> byte[]"Hello world" -->boolean[][]
byte[] contentBytes = content.getBytes("UTF-8");
boolean[][] codeOut = qrCodeHandler.calQrcode(contentBytes);
int imgSize = 67 + 12*(size -1) ;
//BufferedImage:内存中的图片
bufImg = new BufferedImage(imgSize,imgSize,BufferedImage.TYPE_INT_RGB );//red green blue
//创建一个画板
Graphics2D gs = bufImg.createGraphics();
gs.setBackground(Color.WHITE);//将画板的背景色设置为白色
gs.clearRect( 0,0, imgSize,imgSize); //初始化
gs.setColor(Color.BLACK);//设置 画板上 图像的颜色(二维码的颜色)
int pixoff = 2 ;
for(int j=0;j<codeOut.length;j++) {
for(int i=0;i<codeOut.length;i++) {
if(codeOut[j][i]) {
gs.fillRect(j*3+pixoff , i*3+pixoff, 3, 3);
}
}
}
//增加LOGO
//将硬盘中的src/logo.png 加载为一个Image对象
Image logo = ImageIO.read(new File("/src/logo.png") ) ;
int maxHeight = bufImg.getHeight();
int maxWdith = bufImg.getWidth();
//在已生成的二维码上 画logo
gs.drawImage(logo,imgSize/5*2,imgSize/5*2, maxWdith/5,maxHeight/5 ,null) ;
gs.dispose(); //释放空间
bufImg.flush(); //清理
return bufImg ;
}
}
上面那个是网上找的没用过 比我自己做的样式全一些就没有复我的代码
第二种:借助Google提供的ZXing Core工具包zxing3.3.1.jar 自定义背景 logo
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javafx.scene.text.Font;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.swetake.util.Qrcode;
/**
* 生成二维码(QRCode)图片
* @author GYF
* @date 2017年12月18日 下午15:43:17
* @version 1.0
*/
public class ZXingBackGroundUtils {
private static final int QRCOLOR = 0xFF000000; // 默认是黑色
private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
private static final int WIDTH = 200; // 二维码宽
private static final int HEIGHT = 200; // 二维码高
// 用于设置QR二维码参数
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
put(EncodeHintType.MARGIN, 0);
}
};
// 生成带logo的二维码图片
/***
*@param logoFile logo图地址
* @param codeFile 二维码生成地址
* @param qrUrl 扫描二维码方位地址
* */
public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
}
}
int width = image.getWidth();
int height = image.getHeight();
if (Objects.nonNull(logoFile) && logoFile.exists()) {
// 构建绘图对象
Graphics2D g = image.createGraphics();
// 读取Logo图片
BufferedImage logo = ImageIO.read(logoFile);
// 开始绘制logo图片
g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 3 / 10, height * 3 / 10, null);
g.dispose();
logo.flush();
}
image.flush();
ImageIO.write(image, "png", codeFile); // TODO
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 二维码嵌套背景图的方法
*@param bigPath 背景图 - 可传网络地址
*@param smallPath 二维码地址 - 可传网络地址
*@param newFilePath 生成新图片的地址
* @param x 二维码x坐标
* @param y 二维码y坐标
* */
public static void mergeImage(String bigPath, String smallPath, String newFilePath,String x, String y) throws IOException {
try {
BufferedImage small;
BufferedImage big;
if (bigPath.contains("http://") || bigPath.contains("https://")) {
URL url = new URL(bigPath);
big = ImageIO.read(url);
} else {
big = ImageIO.read(new File(bigPath));
}
if (smallPath.contains("http://") || smallPath.contains("https://")) {
URL url = new URL(smallPath);
small = ImageIO.read(url);
} else {
small = ImageIO.read(new File(smallPath));
}
Graphics2D g = big.createGraphics();
float fx = Float.parseFloat(x);
float fy = Float.parseFloat(y);
int x_i = (int) fx;
int y_i = (int) fy;
g.drawImage(small, x_i, y_i, small.getWidth(), small.getHeight(), null);
g.dispose();
ImageIO.write(big, "png", new File(newFilePath));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
//头像logo
String logoPath = "E:" + File.separator + "code" + File.separator +"logo2.jpg";
File logoFile = new File(logoPath);
//生成二维码地址
String imgPath = "E:\\code\\"+new Date().getTime()+".jpg";
File QrCodeFile = new File(imgPath);
String url = "https://www.baidu.com/";
drawLogoQRCode(logoFile, QrCodeFile, url);
String beijing = "E:" + File.separator + "code" + File.separator +"beijing.png";
String imgPath1 = "E:\\code\\"+new Date().getTime()+".jpg";
System.out.println(imgPath1);
mergeImage(beijing,imgPath, imgPath1,"350", "800");
}
}
借助Google提供的ZXing Core工具包zxing3.3.1.jar来解析二维码
public static void readQRCode(){
MultiFormatReader formatReader = new MultiFormatReader();
String path = "E:" + File.separator + "code" + File.separator +"3.jpg";
File file = new File(path);
try {
Map map = new HashMap();
map.put(EncodeHintType.CHARACTER_SET,"utf-8");
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Result decode = formatReader.decode(binaryBitmap,map);
System.err.println(decode.toString());
System.err.println(decode.getBarcodeFormat());
} catch (Exception e) {
e.printStackTrace();
}
}
我个人比较喜欢用ZXing是google开发的 这个在设置背景 和解析二维码方面感觉比日本那个开发的好些(纯属个人意见)