首先声明我们通篇用的都是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 类
package com.chinasie.barcodescanplugin;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
/**
* Created by HanWeijia on 2017/2/4.
*/
public class QRCodeUtil {
private static int QR_WIDTH = 300;
private static int QR_HEIGHT = 300;
/**
* 生成二维码Bitmap
*
* @param content 内容
* @param widthPix 图片宽度
* @param heightPix 图片高度
* @param logoBm 二维码中心的Logo图标(可以为null)
* @param filePath 用于存储二维码图片的文件路径
* @return 生成二维码及保存文件是否成功
*/
public static Bitmap createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
try {
if (content == null || "".equals(content)) {
return null;
}
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
// hints.put(EncodeHintType.MARGIN, 2); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 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是没有任何压缩的,内存消耗巨大!
return bitmap;//!= null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 在二维码中间添加Logo图案
*/
private static Bitmap addLogo(Bitmap src, Bitmap logo) {
if (src == null) {
return null;
}
if (logo == null) {
return src;
}
//获取图片的宽高
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int logoWidth = logo.getWidth();
int logoHeight = logo.getHeight();
if (srcWidth == 0 || srcHeight == 0) {
return null;
}
if (logoWidth == 0 || logoHeight == 0) {
return src;
}
//logo大小为二维码整体大小的1/5
float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try {
Canvas canvas = new Canvas(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();
}
return bitmap;
}
/**
* 生成普通的二维码
* 要转换的地址或字符串,可以是中文
* @param url
*/
public static Bitmap createQRImage(String url)
{
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, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
//下面这里按照二维码的算法,逐个生成二维码的图片,
//两个for循环是图片横列扫描的结果
for (int y = 0; y < QR_HEIGHT; y++)
{
for (int x = 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);
return bitmap;
}
catch (WriterException e)
{
e.printStackTrace();
}
return null;
}
}
注释已经很明了了 ,这个工具类我就不多说了,就下来说说调用,当然也很简单
package com.chinasie.barcodescanplugin;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.zxing.activity.CaptureActivity;
import java.io.File;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static String TAB = MainActivity.class.getSimpleName();
//显示扫描结果
private EditText editText = null;
//扫描按钮
private Button btnScan = null;
//普通图片
private ImageView imageNormal = null;
//普通按钮
private Button buttonNormal = null;
//特按钮
private Button buttonAndCenter = null;
//有中心图片
private ImageView imageWithCenter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
* 点击时间响应
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnScan:
try {
//打开扫描界面扫描条形码或二维码
Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(openCameraIntent, 0);
}
catch (Exception ex){
Log.e(TAB,ex.getMessage());
ex.printStackTrace();
}
break;
case R.id.button:
//普通的二维码图片显示到一个ImageView上面
imageNormal.setImageBitmap(QRCodeUtil.createQRImage("123456789"));
break;
case R.id.buttonAndCenter:
final String filePath = File.separator
+ "qr_" + System.currentTimeMillis() + ".jpg";
//二维码图片较大时,生成图片、保存文件的时间可能较长,因此放在新线程中
new Thread(new Runnable() {
@Override
public void run() {
final Bitmap success = QRCodeUtil.createQRImage("strUrl", 800,800,BitmapFactory.decodeResource(getResources(), R.drawable.gg),filePath);
if (success!=null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//带有中心图片的二维码显示在 imageWithCenter 上
imageWithCenter.setImageBitmap(success);
}
});
}
}
}).start();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//处理扫描结果(在界面上显示)
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString("result");
editText.setText(scanResult);
}
}
/**
* 初始化View
*/
private void initView(){
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);
}
}
这里也不过多说了,淡然如果有找不到上述资源的可以下载我的源代码,里面都有。。