您的位置:首页 > 编程语言 > Java开发

JAVA中生成、解析二维码图片的方法

2017-09-18 18:45 513 查看
  JAVA中生成、解析二维码的方法并不复杂,使用google的zxing包就可以实现。下面的方法包含了生成二维码、在中间附加logo、添加文字功能,并有解析二维码的方法。

一、下载zxing的架包,并导入项目中,如下:



最主要的包都在com.google.zxing.core下。如果是maven项目,maven依赖如下:

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>


二、二维码生成,附上代码例子,如下:

public class TestQRcode {

private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static final int margin = 0;
private static final int LogoPart = 4;

/**
* 生成二维码矩阵信息
* @param content 二维码图片内容
* @param width 二维码图片宽度
* @param height 二维码图片高度
*/
public static BitMatrix setBitMatrix(String content, int width, int height){
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 指定编码方式,防止中文乱码
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 指定纠错等级
hints.put(EncodeHintType.MARGIN, margin); // 指定二维码四周白色区域大小
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
return bitMatrix;
}

/**
* 将二维码图片输出
* @param matrix 二维码矩阵信息
* @param format 图片格式
* @param outStream 输出流
* @param logoPath logo图片路径
*/
public static void writeToFile(BitMatrix matrix, String format, OutputStream outStream, String logoPath) throws IOException {
BufferedImage image = toBufferedImage(matrix);
// 加入LOGO水印效果
if (StringUtils.isNotBlank(logoPath)) {
image = addLogo(image, logoPath);
}
ImageIO.write(image, format, outStream);
}

/**
* 生成二维码图片
* @param matrix 二维码矩阵信息
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
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;
}

/**
* 在二维码图片中添加logo图片
* @param image 二维码图片
* @param logoPath logo图片路径
*/
public static BufferedImage addLogo(BufferedImage image, String logoPath) throws IOException {
Graphics2D g = image.createGraphics();
BufferedImage logoImage = ImageIO.read(new File(logoPath));
// 计算logo图片大小,可适应长方形图片,根据较短边生成正方形
int width = image.getWidth() < image.getHeight() ? image.getWidth() / LogoPart : image.getHeight() / LogoPart;
int height = width;
// 计算logo图片放置位置
int x = (image.getWidth() - width) / 2;
int y = (image.getHeight() - height) / 2;
// 在二维码图片上绘制logo图片
g.drawImage(logoImage, x, y, width, height, null);
// 绘制logo边框,可选
//        g.drawRoundRect(x, y, logoImage.getWidth(), logoImage.getHeight(), 10, 10);
g.setStroke(new BasicStroke(2)); // 画笔粗细
g.setColor(Color.WHITE); // 边框颜色
g.drawRect(x, y, width, height); // 矩形边框
logoImage.flush();
g.dispose();
return image;
}

/**
* 为图片添加文字
* @param pressText 文字
* @param newImage 带文字的图片
* @param targetImage 需要添加文字的图片
* @param fontStyle 字体风格
* @param color 字体颜色
* @param fontSize 字体大小
* @param width 图片宽度
* @param height 图片高度
*/
public static void pressText(String pressText, String newImage, String targetImage, int fontStyle, Color color, int fontSize, int width, int height) {
// 计算文字开始的位置
// x开始的位置:(图片宽度-字体大小*字的个数)/2
int startX = (width-(fontSize*pressText.length()))/2;
// y开始的位置:图片高度-(图片高度-图片宽度)/2
int startY = height-(height-width)/2 + fontSize;
try {
File file = new File(targetImage);
BufferedImage src = ImageIO.read(file);
int imageW = src.getWidth(null);
int imageH = src.getHeight(null);
BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, imageW, imageH, null);
g.setColor(color);
g.setFont(new Font(null, fontStyle, fontSize));
g.drawString(pressText, startX, startY);
g.dispose();
FileOutputStream out = new FileOutputStream(newImage);
ImageIO.write(image, "png", out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String content = "http://www.baidu.com";
String logoPath = "C:/logo.png";
String format = "jpg";
int width = 180;
int height = 220;
BitMatrix bitMatrix = setBitMatrix(content, width, height);
// 可通过输出流输出到页面,也可直接保存到文件
OutputStream outStream = null;
String path = "c:/qr"+new Date().getTime()+".png";
try {
outStream = new FileOutputStream(new File(path));
writeToFile(bitMatrix, format, outStream, logoPath);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 添加文字效果
int fontSize = 12; // 字体大小
int fontStyle = 1; // 字体风格
String text = "测试二维码";
String withTextPath = "c:/text"+new Date().getTime()+".png";
pressText(text, withTextPath, path, fontStyle, Color.BLUE, fontSize, width, height);
}
}


三、生成效果如下:



  代码注释比较详细,就不多解释啦,大家可以根据自己的需求进行调整。

PS:

1、如果想生成带文字的二维码,记得要用长方形图片,为文字预留空间。

2、要生成带logo的二维码要注意遮挡率的问题,setBitMatrix()方法中ErrorCorrectionLevel.H这个纠错等级参数决定了二维码可被遮挡率。对应如下:

L水平7%的字码可被修正
M水平15%的字码可被修正
Q水平25%的字码可被修正
H水平30%的字码可被修正
四、二维码解析,附上代码例子,如下:

/**
* 解析二维码图片
* @param filePath 图片路径
*/
public static String decodeQR(String filePath) {
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "二维码图片不存在!";
}
String content = "";
EnumMap<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 指定编码方式,防止中文乱码
try {
BufferedImage image = ImageIO.read(new FileInputStream(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(binaryBitmap, hints);
content = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}


  可以从二维码图片中解析出具体的内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: