[学习笔记]Java生成二维码

本文介绍了一个用于生成二维码的实用工具类,该工具类能够创建指定内容的二维码,并将其保存为图片文件。文章详细展示了如何使用Java编程语言及Google ZXing库来实现这一功能。
package com.skyland.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

/**

* @author Francis-ChinaFeng
* @version 1.0 2013-12-12
*/
public class QRCodeUtils {

private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static final int WIDTH_HEIGHT = 300;
private static final String FORMAT = "png";

/**
* 获得生成二维码的路径
* @param contents
* @param dir
* @param fileName
* @return
*/
public static File createQRCode(String contents, String dir, String fileName) {
return createQRCode(contents, dir, fileName, FORMAT);
}

/**
* 获得生成二维码的路径
* @param contents
* @param dir
* @param fileName
* @return
*/
public static File createQRCode(String contents, String dir, String fileName, String format) {
StringBuilder builder = new StringBuilder();
builder.append(dir);
builder.append(File.separator);
builder.append(fileName);
builder.append(".");
builder.append(FORMAT);
String path = builder.toString();
File file = null;
try {
file = IOUtils.createNewFile(path);
BitMatrix matrix = createQRCode(contents);
BufferedImage buffered = getBufferedImage(matrix);
if (!ImageIO.write(buffered, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} catch (IOException e) {
e.printStackTrace(); 
} catch (WriterException e) {
e.printStackTrace();
}
if (file != null && file.exists() && file.length() > 0) {
return file;
}
return null;
}

/**
* 获得生成二维码的Bitmap对象
* @param contents
* @return
* @throws WriterException 
*/
private static BitMatrix createQRCode(String contents) throws WriterException {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix matrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, WIDTH_HEIGHT, WIDTH_HEIGHT);
return matrix;
}

/**
* 获取BufferedImage数据对象
* @param matrix
* @return
*/
private static BufferedImage getBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage buffered = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
buffered.setRGB(i, j, matrix.get(i, j) ? BLACK : WHITE);
}
}
return buffered;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值