package com.company.utils;
package com.shixun.ewifi.utils;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码工具类 二维码生成 解析 带图片与不带图片的二维码
*
*/
public class QrcodeUtils {
// 默认宽为300
private static Integer WIDTH = 300;
// 默认高为300
private static Integer HEIGHT = 300;
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// 默认二维码图片格式
private String IMAGEFORMAT = "png";
private static final String IMAGE_FORMAT= "JPG";
// 默认二维码字符编码
private static String CHARTYPE = "utf-8";
// 默认二维码的容错级别
private ErrorCorrectionLevel corretionLevel = ErrorCorrectionLevel.H;
// 二维码与图片的边缘
private static Integer MARGIN = 1;
// 二维码参数
private Map<EncodeHintType, Object> encodeHits = new HashMap<EncodeHintType,Object>();
public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType,
ErrorCorrectionLevel corretionLevel, Integer margin) {
if (WIDTH != null) {
this.WIDTH = WIDTH;
}
if (HEIGHT != null) {
this.HEIGHT = HEIGHT;
}
if (IMAGEFORMAT != null) {
this.IMAGEFORMAT = IMAGEFORMAT;
}
if (CHARTYPE != null) {
this.CHARTYPE = CHARTYPE;
}
if (corretionLevel != null) {
this.corretionLevel = corretionLevel;
}
if (MARGIN != null) {
this.MARGIN = MARGIN;
}
}
public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType,
ErrorCorrectionLevel corretionLevel) {
this(width, height, imageFormat, charType, corretionLevel, null);
}
public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType, Integer margin) {
this(width, height, imageFormat, charType, null, margin);
}
public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType) {
this(width, height, imageFormat, charType, null, null);
}
public QrcodeUtils(Integer width, Integer height, String imageFormat) {
this(width, height, imageFormat, null, null, null);
}
public QrcodeUtils(Integer width, Integer height) {
this(width, height, null, null, null, null);
}
public QrcodeUtils() {
}
// 初始化二维码的参数
private void initialParamers() {
// 字符编码
encodeHits.put(EncodeHintType.CHARACTER_SET, this.CHARTYPE);
// 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
encodeHits.put(EncodeHintType.ERROR_CORRECTION, this.corretionLevel);
// 二维码与图片边距
encodeHits.put(EncodeHintType.MARGIN, MARGIN);
}
// 得到二维码图片
// public BufferedImage getBufferedImage(String content) {
// initialParamers();
// BufferedImage bufferedImage = null;
// try {
// BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width,
// this.height, this.encodeHits);
// bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
// } catch (WriterException e) {
// e.printStackTrace();
// return null;
// }
// return bufferedImage;
// }
// 将二维码保存到输出流中
// public void writeToStream(String content, OutputStream os) {
// initialParamers();
// try {
// BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,
// this.encodeHits);
// MatrixToImageWriter.writeToStream(matrix, this.imageFormat, os);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// 将二维码图片保存为文件
// public void createQrImage(String content, File file) {
// initialParamers();
// try {
// BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,this.encodeHits);
// MatrixToImageWriter.writeToFile(matrix, this.imageFormat, file);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// 将二维码图片保存到指定路径
public void createQrImage(String content, String path) {
initialParamers();
try {
BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.WIDTH, this.HEIGHT,this.encodeHits);
MatrixToImageWriter.writeToFile(matrix, this.IMAGEFORMAT, new File(path));
} catch (Exception e) {
e.printStackTrace();
}
}
//识别图片二维码
public String decodeQrImage(File file){
String content=null;
try {
BufferedImage bufferedImage=ImageIO.read(new FileInputStream(file));
LuminanceSource source=new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer=new HybridBinarizer(source);
BinaryBitmap image=new BinaryBitmap(binarizer);
Map<DecodeHintType,Object> decodeHits=new HashMap<DecodeHintType,Object>();
decodeHits.put(DecodeHintType.CHARACTER_SET, this.CHARTYPE);
Result result=new MultiFormatReader().decode(image, decodeHits);
content=result.getText();
}catch (Exception e) {
e.printStackTrace();
}
return content;
}
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARTYPE);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QrcodeUtils.insertImage(image, imgPath, needCompress);
return image;
}
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
public static void encode(String content, String imgPath, String destPath,
boolean needCompress) throws Exception {
BufferedImage image = QrcodeUtils.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999) + ".jpg";
ImageIO.write(image, IMAGE_FORMAT, new File(destPath + "/" + file));
}
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
public Integer getWidth() {
return WIDTH;
}
public void setWidth(Integer WIDTH) {
this.WIDTH = WIDTH;
}
public Integer getHeight() {
return HEIGHT;
}
public void setHeight(Integer HEIGHT) {
this.HEIGHT = HEIGHT;
}
public String getImageFormat() {
return IMAGEFORMAT;
}
public void setImageFormat(String IMAGEFORMAT) {
this.IMAGEFORMAT = IMAGEFORMAT;
}
public String getCharType() {
return CHARTYPE;
}
public void setCharType(String CHARTYPE) {
this.CHARTYPE = CHARTYPE;
}
public ErrorCorrectionLevel getCorretionLevel() {
return corretionLevel;
}
public void setCorretionLevel(ErrorCorrectionLevel corretionLevel) {
this.corretionLevel = corretionLevel;
}
public Integer getMargin() {
return MARGIN;
}
public void setMargin(Integer MARGIN) {
this.MARGIN = MARGIN;
}
public Map<EncodeHintType, Object> getHits() {
return encodeHits;
}
public void setHits(Map<EncodeHintType, Object> hits) {
this.encodeHits = hits;
}
//main方法测试工具类
public static void main(String[] args) throws Exception {
String text = "鲲鹏展翅";
String path2="D:/MyWorkDoc/test.png";
QrcodeUtils qrCode=new QrcodeUtils(300,300);
//设置二维码的边缘为1
qrCode.setMargin(MARGIN);
//输出到桌面
//String path=System.getProperty("user.home")+File.separator+"Desktop"+File.separator+"test.png";
//创建图片二维码
//qrCode.createQrImage(text, path2);//路径指定到文件名
//QrcodeUtils.encode(text, "d:/MyWorkDoc/kun.jpg", path2, true);//携带LOGO生成二维码 路径指定文件夹
//QrcodeUtils.encode(text,"",path2,true);//不携带LOGO生成二维码 路径指定文件夹
//识别图片二维码的内容
System.out.println(qrCode.decodeQrImage(new File(path2)));//路径指定到文件名
}
}
package com.company.utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;
public class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {
}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format "
+ format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format,
OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format "
+ format);
}
}
}
有重复代码大家自己看一下