【www.bbyears.com--Google】
首先声明我们通篇用的都是Google开源框架Zxing,要实现的功能有三个 ,生成普通二维码、生成带有中心图片Logo 的二维码,扫描解析二维码,直接上效果图吧
首先我们需要一个这样的 Zxing 的包类似于这样
接下来需要引入资源
1.drawable 中引入图片 navbar.png
2.layout中引入camera.xml、main.xml、qrcode_capture_page.xml
3.创建raw文件夹并添加beep.ogg 扫描声音
4.合并color.xml,copy ids.xml到values目录中
引入文件之后的效果图是这样的
接下来是 QRCodeUtil 类
代码如下packagecom.chinasie.barcodescanplugin;
importandroid.graphics.Bitmap;
importandroid.graphics.Canvas;
importcom.google.zxing.BarcodeFormat;
importcom.google.zxing.EncodeHintType;
importcom.google.zxing.WriterException;
importcom.google.zxing.common.BitMatrix;
importcom.google.zxing.qrcode.QRCodeWriter;
importcom.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.HashMap;
importjava.util.Hashtable;
importjava.util.Map;
/**
* Created by HanWeijia on 2017/2/4.
*/
publicclassQRCodeUtil {
privatestaticintQR_WIDTH =300;
privatestaticintQR_HEIGHT =300;
/**
* 生成二维码Bitmap
*
* @param content 内容
* @param widthPix 图片宽度
* @param heightPix 图片高度
* @param logoBm 二维码中心的Logo图标(可以为null)
* @param filePath 用于存储二维码图片的文件路径
* @return 生成二维码及保存文件是否成功
*/
publicstaticBitmap createQRImage(String content,intwidthPix,intheightPix, Bitmap logoBm, String filePath) {
try{
if(content ==null||"".equals(content)) {
returnnull;
}
//配置参数
Map
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
// hints.put(EncodeHintType.MARGIN, 2); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix =newQRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
int[] pixels =newint[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for(inty =0; y < heightPix; y++) {
for(intx =0; x < widthPix; x++) {
if(bitMatrix.get(x, y)) {
pixels[y * widthPix + x] =0xff000000;
}else{
pixels[y * widthPix + x] =0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels,0, widthPix,0,0, widthPix, heightPix);
if(logoBm !=null) {
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
returnbitmap;//!= null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
}catch(WriterException e) {
e.printStackTrace();
}
returnnull;
}
/**
* 在二维码中间添加Logo图案
*/
privatestaticBitmap addLogo(Bitmap src, Bitmap logo) {
if(src ==null) {
returnnull;
}
if(logo ==null) {
returnsrc;
}
//获取图片的宽高
intsrcWidth = src.getWidth();
intsrcHeight = src.getHeight();
intlogoWidth = logo.getWidth();
intlogoHeight = logo.getHeight();
if(srcWidth ==0|| srcHeight ==0) {
returnnull;
}
if(logoWidth ==0|| logoHeight ==0) {
returnsrc;
}
//logo大小为二维码整体大小的1/5
floatscaleFactor = srcWidth *1.0f /5/ logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try{
Canvas canvas =newCanvas(bitmap);
canvas.drawBitmap(src,0,0,null);
canvas.scale(scaleFactor, scaleFactor, srcWidth /2, srcHeight /2);
canvas.drawBitmap(logo, (srcWidth - logoWidth) /2, (srcHeight - logoHeight) /2,null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
}catch(Exception e) {
bitmap =null;
e.getStackTrace();
}
returnbitmap;
}
/**
* 生成普通的二维码
* 要转换的地址或字符串,可以是中文
* @param url
*/
publicstaticBitmap createQRImage(String url)
{
try
{
//判断URL合法性
if(url ==null||"".equals(url) || url.length()<1)
{
returnnull;
}
Hashtable
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
//图像数据转换,使用了矩阵转换
BitMatrix bitMatrix =newQRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels =newint[QR_WIDTH * QR_HEIGHT];
//下面这里按照二维码的算法,逐个生成二维码的图片,
//两个for循环是图片横列扫描的结果
for(inty =0; y < QR_HEIGHT; y++)
{
for(intx =0; x < QR_WIDTH; x++)
{
if(bitMatrix.get(x, y))
{
pixels[y * QR_WIDTH + x] =0xff000000;
}
else
{
pixels[y * QR_WIDTH + x] =0xffffffff;
}
}
}
//生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels,0, QR_WIDTH,0,0, QR_WIDTH, QR_HEIGHT);
returnbitmap;
}
catch(WriterException e)
{
e.printStackTrace();
}
returnnull;
}
}
注释已经很明了了 ,这个工具类我就不多说了,就下来说说调用,当然也很简单
代码如下packagecom.chinasie.barcodescanplugin;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.ImageView;
importcom.zxing.activity.CaptureActivity;
importjava.io.File;
publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener {
privatestaticString TAB = MainActivity.class.getSimpleName();
//显示扫描结果
privateEditText editText =null;
//扫描按钮
privateButton btnScan =null;
//普通图片
privateImageView imageNormal =null;
//普通按钮
privateButton buttonNormal =null;
//特按钮
privateButton buttonAndCenter =null;
//有中心图片
privateImageView imageWithCenter =null;
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
* 点击时间响应
* @param v
*/
@Override
publicvoidonClick(View v) {
switch(v.getId()){
caseR.id.btnScan:
try{
//打开扫描界面扫描条形码或二维码
Intent openCameraIntent =newIntent(MainActivity.this, CaptureActivity.class);
startActivityForResult(openCameraIntent,0);
}
catch(Exception ex){
Log.e(TAB,ex.getMessage());
ex.printStackTrace();
}
break;
caseR.id.button:
//普通的二维码图片显示到一个ImageView上面
imageNormal.setImageBitmap(QRCodeUtil.createQRImage("123456789"));
break;
caseR.id.buttonAndCenter:
finalString filePath = File.separator
+"qr_"+ System.currentTimeMillis() +".jpg";
//二维码图片较大时,生成图片、保存文件的时间可能较长,因此放在新线程中
newThread(newRunnable() {
@Override
publicvoidrun() {
finalBitmap success = QRCodeUtil.createQRImage("strUrl",800,800,BitmapFactory.decodeResource(getResources(), R.drawable.gg),filePath);
if(success!=null) {
runOnUiThread(newRunnable() {
@Override
publicvoidrun() {
//带有中心图片的二维码显示在 imageWithCenter 上
imageWithCenter.setImageBitmap(success);
}
});
}
}
}).start();
break;
}
}
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//处理扫描结果(在界面上显示)
if(resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString("result");
editText.setText(scanResult);
}
}
/**
* 初始化View
*/
privatevoidinitView(){
editText = (EditText)this.findViewById(R.id.editText);
imageWithCenter = (ImageView)findViewById(R.id.imageAndCenter);
imageNormal = (ImageView)this.findViewById(R.id.image) ;
btnScan = (Button)this.findViewById(R.id.btnScan);
buttonNormal = (Button)this.findViewById(R.id.button);
buttonAndCenter = (Button)findViewById(R.id.buttonAndCenter);
btnScan.setOnClickListener(this);
buttonNormal.setOnClickListener(this);
buttonAndCenter.setOnClickListener(this);
}
}
这里也不过多说了,淡然如果有找不到上述资源的可以下载我的源代码,里面都有。。
点击下载源码