您的位置:首页 > 其它

普通二维码和带图片二维码生成

2016-02-18 14:51 260 查看
参考:/article/1915038.html

依赖于Google开源框架zxing

下载core.jar http://maven.outofmemory.cn/com.google.zxing/core/3.1.0/ href="http://maven.outofmemory.cn/com.google.zxing/core/3.1.0/" target=_blank>

普通二维码

<span style="white-space:pre">	</span>/*
* url:扫描文本信息 width:生成二维码宽 height:高
*/
public Bitmap createQRImage(String url, final int width, final int height) {
try {
// 判断URL合法性
if (url == null || "".equals(url) || url.length() < 1) {
return null;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(url,
BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}


生成带图片的二维码

图片像素不能太高,若要大些,相应的二维码尺寸也要增大,否则无法识别,不能被扫描出来

private int IMAGE_HALFWIDTH = 10;// 中间图片的宽度

/*
* string:文本信息
* mBitmap:要插入的图片
*/

public Bitmap createCode(String string, Bitmap mBitmap, BarcodeFormat format)
throws WriterException {
Matrix m = new Matrix();
float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
float sy = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getHeight();
m.setScale(sx, sy);// 设置缩放信息
// 将logo图片按martix设置的信息缩放
mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
mBitmap.getHeight(), m, false);
MultiFormatWriter writer = new MultiFormatWriter();
Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();
hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 设置字符编码
BitMatrix matrix = writer.encode(string, format, 400, 400, hst);// 生成二维码矩阵信息
int width = matrix.getWidth();// 矩阵高度
int height = matrix.getHeight();// 矩阵宽度
int halfW = width / 2;
int halfH = height / 2;
int[] pixels = new int[width * height];// 定义数组长度为矩阵高度*矩阵宽度,用于记录矩阵中像素信息
for (int y = 0; y < height; y++) {// 从行开始迭代矩阵
for (int x = 0; x < width; x++) {// 迭代列
if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
&& y > halfH - IMAGE_HALFWIDTH
&& y < halfH + IMAGE_HALFWIDTH) {// 该位置用于存放图片信息
// 记录图片每个像素信息
pixels[y * width + x] = mBitmap.getPixel(x - halfW
+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
} else {
if (matrix.get(x, y)) {// 如果有黑块点,记录信息
pixels[y * width + x] = 0xff000000;// 记录黑块信息
}
}

}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
// 通过像素数组生成bitmap
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: