/**
* Copyright [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package framework.webapp.commons.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
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.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
/**
* **************************************************
* @description 二维码生成工具类
* @author [email protected]
* @version 2.0, 2017-02-09
* @see HISTORY
* <p>
* Date Desc Author Operation
* </p>
* <p>
* 2015-06-12 创建文件 karl create
* </p>
* <p>
* 2017-02-09 修改 karl 加入无中间文件,直接生成图片base64编码
* </p>
* @since 2017 Phyrose Science & Technology (Kunming) Co., Ltd.
* ************************************************
*/
public class QRCodeUtil {
/**
* 二维码宽
*/
private static final int QR_CODE_IMG_WIDTH = 430;
/**
* 二维码高
*/
private static final int QR_CODE_IMG_HEIGHT = 430;
/**
* 根据文件生成二维码
*
* @param file file
* @return Result
*/
public static Result QRDeCodeFromFile(File file) {
Result result = null;
try {
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
result = formatReader.decode(binaryBitmap, hints);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
/**
* 根据 URL 生成二维码
*
* @param url
* @return Result
*/
public static Result QRDeCodeFromURL(URL url) {
Result result = null;
try {
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(url);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
result = formatReader.decode(binaryBitmap, hints);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
/**
* 字符串内容生成二维码并输出到文件
*
* @param content
* @param outFile
*/
public static void QRCodeToFile(String content, File outFile) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_IMG_WIDTH, QR_CODE_IMG_HEIGHT, hints);
writeToFile(bitMatrix, "jpg", outFile);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 字符串内容生成二维码并写入输出流
*
* @param content
* @param os
*/
public static void QRCodeToStream(String content, OutputStream os) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_IMG_WIDTH, QR_CODE_IMG_HEIGHT, hints);
writeToStream(bitMatrix, "jpg", os);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 字符串内容生成二维码并输出为base64编码的图片,可直接放入img标签的src中
*
* @param content
* @param width 字段宽度(高度)
* @return
*/
public static String QRCodeToBase64(String content, int width) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, width, hints);
return writeToBase64(bitMatrix);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 字符串内容生成二维码并输出到文件
*
* @param content
* @param outFile
* @param logoFile logo显示在二维码正中间
*/
public static void QRCodeToFileWithLogo(String content, File outFile, File logoFile) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_IMG_WIDTH, QR_CODE_IMG_HEIGHT, hints);
writeToFileWithLogo(bitMatrix, "jpg", outFile, logoFile);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 字符串内容生成二维码并输出到文件
*
* @param content
* @param outFile
* @param logoImg logo显示在二维码正中间
*/
public static void QRCodeToFileWithLogoImage(String content, File outFile, Image logoImg) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_IMG_WIDTH, QR_CODE_IMG_HEIGHT, hints);
writeToFileWithLogoImage(bitMatrix, "jpg", outFile, logoImg);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 处理过程需要的中间类封装
*/
static final class BufferedImageLuminanceSource extends LuminanceSource {
private final BufferedImage image;
private final int left;
private final int top;
public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}
public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
super(width, height);
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
for (int y = top; y < top + height; y++) {
for (int x = left; x < left + width; x++) {
if ((image.getRGB(x, y) & 0xFF000000) == 0) {
image.setRGB(x, y, 0xFFFFFFFF); // = white
}
}
}
this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image, 0, 0, null);
this.left = left;
this.top = top;
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}
@Override
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}
@Override
public boolean isCropSupported() {
return true;
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
}
@Override
public boolean isRotateSupported() {
return true;
}
@Override
public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}
}
//内部变量和方法
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private 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;
}
private 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);
}
}
private static void writeToFileWithLogo(BitMatrix matrix, String format, File outFile, File logoFile)
throws IOException {
BufferedImage bufImg = toBufferedImage(matrix);
Graphics2D gs = bufImg.createGraphics();
//实例化一个logo Image对象。
BufferedImage logoImg = ImageIO.read(logoFile);
int offset = bufImg.getWidth() / 12;
int x = bufImg.getWidth() / 2 - offset;
int y = bufImg.getHeight() / 2 - offset;
int w = offset * 2;
int rectWidth = offset / 3;
RoundRectangle2D.Double rect = new RoundRectangle2D.Double(x - 1, y - 1, w + 1, w + 1, rectWidth, rectWidth);
gs.drawImage(logoImg.getScaledInstance(w, w, Image.SCALE_SMOOTH), x, y, w, w, null);
// 设置画笔颜色为白色
gs.setColor(Color.WHITE);
gs.setStroke(new BasicStroke(3));
gs.draw(rect);
gs.dispose();
bufImg.flush();
if (!ImageIO.write(bufImg, format, outFile)) {
throw new IOException("Could not write an image of format " + format + " to " + outFile);
}
}
private static void writeToFileWithLogoImage(BitMatrix matrix, String format, File outFile, Image logoImg)
throws IOException {
BufferedImage bufImg = toBufferedImage(matrix);
Graphics2D gs = bufImg.createGraphics();
int offset = bufImg.getWidth() / 12;
int x = bufImg.getWidth() / 2 - offset;
int y = bufImg.getHeight() / 2 - offset;
int w = offset * 2;
int rectWidth = offset / 3;
RoundRectangle2D.Double rect = new RoundRectangle2D.Double(x - 1, y - 1, w + 1, w + 1, rectWidth, rectWidth);
gs.drawImage(logoImg.getScaledInstance(w, w, Image.SCALE_SMOOTH), x, y, w, w, null);
// 设置画笔颜色为白色
gs.setColor(Color.WHITE);
gs.setStroke(new BasicStroke(3));
gs.draw(rect);
gs.dispose();
bufImg.flush();
if (!ImageIO.write(bufImg, format, outFile)) {
throw new IOException("Could not write an image of format " + format + " to " + outFile);
}
}
private 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);
}
}
private static String writeToBase64(BitMatrix matrix)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!ImageIO.write(image, "jpg", baos)) {
throw new IOException("Could not write an image of format jpg");
}
return "data:image/png;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
maven依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
<type>jar</type>
</dependency>