Android zxing 解析二维码,生成二维码极简demo

zxing 官方的代码很多,看起来很费劲,此demo只抽取了有用的部分,实现了相机预览解码,解析本地二维码,生成二维码三个功能。

简化后的结构如下:

废话少说直接上代码:

BaseDecodeHandler:
package com.song.zxing.decode;

import android.graphics.Bitmap;
import android.os.Bundle;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/16.
 */
public class BaseDecodeHandler {
    MultiFormatReader multiFormatReader;

    public BaseDecodeHandler() {
        initReader();
    }

    private void initReader() {
        multiFormatReader = new MultiFormatReader();
        Map<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
        Collection<BarcodeFormat> decodeFormats = new ArrayList<BarcodeFormat>();
        decodeFormats.addAll(EnumSet.of(BarcodeFormat.QR_CODE));
        decodeFormats.addAll(EnumSet.of(BarcodeFormat.CODABAR));
        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
        multiFormatReader.setHints(hints);
    }

    public Bundle getThumbData(PlanarYUVLuminanceSource source) {
        Bundle bundle = new Bundle();
        int[] pixels = source.renderThumbnail();
        int width = source.getThumbnailWidth();
        int height = source.getThumbnailHeight();
        Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.ARGB_8888);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
        bundle.putByteArray("data", out.toByteArray());
        return bundle;
    }
}

  

PreviewDecodeHandler:
package com.song.zxing.decode;

import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.song.zxing.util.Constant;

/**
 * Created by Administrator on 2015/12/16.
 */
public class PreviewDecodeHandler extends BaseDecodeHandler implements Camera.PreviewCallback {
    private Rect rect;
    private boolean running;
    private Handler handler;

    public PreviewDecodeHandler(Rect rect, Handler handler) {
        this.rect = rect;
        this.handler = handler;
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (running) {
            return;
        }
        decode(data, camera);
    }

    private void decode(byte[] data, Camera camera) {
        Camera.Size size = camera.getParameters().getPreviewSize();
        running = true;
        // 这里需要将获取的data翻转一下,因为相机默认拿的的横屏的数据
        byte[] rotatedData = new byte[data.length];
        for (int y = 0; y < size.height; y++) {
            for (int x = 0; x < size.width; x++)
                rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width];
        }

        // 宽高也要调整
        int tmp = size.width;
        size.width = size.height;
        size.height = tmp;

        Result rawResult = null;
        // Go ahead and assume it‘s YUV rather than die.
        PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(rotatedData, size.width, size.height, rect.left, rect.top, rect.width(), rect.height(), false);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        try {
            rawResult = multiFormatReader.decodeWithState(bitmap);
        } catch (ReaderException re) {
            // continue
        } finally {
            multiFormatReader.reset();
        }
        if (rawResult != null) {
            if (handler != null) {
                Message msg = Message.obtain(handler, Constant.VALUE_DECODE_SUCCESS, rawResult.getText());
//                msg.setData(getThumbData(source)); // 去掉注释可以拿到最终图片
                msg.sendToTarget();
            }
        }
        running = false;
    }
}

  

CameraView:
package com.song.zxing.ui;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.song.zxing.App;
import com.song.zxing.util.AutoFocusManager;

import java.util.List;

/**
 * use decrypted Api mCamera
 */
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private AutoFocusManager autoFocusManager;

    public CameraView(Context context) {
        super(context);
        init();
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CameraView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mHolder = getHolder();
        mHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
            App.toast("相机打开失败");
            ((Activity) getContext()).finish();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mHolder.getSurface() == null) {
            return;
        }
        try {
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(mHolder);
            setPreviewSize();
            start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        release();
        autoFocusManager.stop();
    }

    private void setPreviewSize() {
        if (mCamera == null) return;
        Camera.Parameters parameters = mCamera.getParameters();
        Camera.Size cameraSize = getOptimalPreviewSize(parameters.getSupportedPreviewSizes(), App.getScreenHeight(), App.getScreenWidth());
        Camera.Size pictureSize = getOptimalPreviewSize(parameters.getSupportedPictureSizes(), App.getScreenHeight(), App.getScreenWidth());
        parameters.setPreviewSize(cameraSize.width, cameraSize.height);
        parameters.setPictureSize(pictureSize.width, pictureSize.height);
        mCamera.setParameters(parameters);
    }

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - h) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - h);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - h) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - h);
                }
            }
        }
        return optimalSize;
    }

    public void capture(Camera.PictureCallback callback) {
        if (mCamera != null)
            mCamera.takePicture(null, null, callback);
    }

    public void stopPreview() {
        if (mCamera != null)
            mCamera.stopPreview();
    }

    public void setPreviewCallback(Camera.PreviewCallback callback) {
        if (mCamera != null) {
            mCamera.setPreviewCallback(callback);
        }
    }

    private void start() {
        if (mCamera != null) {
            mCamera.startPreview();
            autoFocusManager = new AutoFocusManager(mCamera);
            if (listener != null) {
                listener.initSuccess();
            }
        }
    }

    public void release() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    InitListener listener;

    public void setInitListener(InitListener listener) {
        this.listener = listener;
    }

    public interface InitListener {
        void initSuccess();
    }
}

  

ScreenOverlay:
package com.song.zxing.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.song.zxing.App;
import com.song.zxing.R;

/**
 * Created by Administrator on 2015/11/4.
 */
public class ScreenOverlay extends View {
    private RectF rectF;
    private Paint paint;
    private Bitmap rectBitmap;
    private Bitmap lineBitmap;
    private int lineOffset = 2;
    private int rectBitmapWidth;
    private int rectBitmapHeight;

    public ScreenOverlay(Context context) {
        super(context);
    }

    public ScreenOverlay(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPoint();
    }

    public ScreenOverlay(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void initPoint() {
        rectBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.qr_capture);
        lineBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.qr_scan_line);
        int mScreenWidth = App.getScreenWidth();
        int mScreenHeight = App.getScreenHeight();
        rectBitmapWidth = rectBitmap.getWidth();
        rectBitmapHeight = rectBitmap.getHeight();
        float left = (mScreenWidth - rectBitmapWidth) / 2;
        float top = (mScreenHeight - rectBitmapHeight - 20) / 2;
        float right = left + rectBitmapWidth;
        float bottom = top + rectBitmapHeight;
        rectF = new RectF(left, top, right, bottom);

        paint = new Paint();
        paint.setColor(Color.parseColor("#60000000"));
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawRect(0, 0, App.getScreenWidth(), rectF.top, paint);
        canvas.drawRect(0, rectF.top, rectF.left, rectF.bottom, paint);
        canvas.drawRect(0, rectF.bottom, App.getScreenWidth(), App.getScreenHeight(), paint);
        canvas.drawRect(rectF.right, rectF.top, App.getScreenWidth(), rectF.bottom, paint);
        canvas.drawBitmap(rectBitmap, rectF.left, rectF.top, paint);
        canvas.drawBitmap(lineBitmap, null, getDstRect(rectF, lineOffset), paint);
        lineOffset = lineOffset >= rectBitmapHeight - 10 ? 10 : lineOffset + 2;
        invalidate();
    }

    private Rect getDstRect(RectF rectF, int offset) {
        Rect rect = new Rect();
        rect.left = (int) rectF.left;
        rect.top = (int) rectF.top + offset;
        rect.bottom = rect.top + App.dp2Px(2);
        rect.right = (int) (rectF.left + rectBitmapWidth);
        return rect;
    }

    public RectF getPreviewRectF() {
        return rectF;
    }

    public Rect getPreviewRect() {
        Rect rect = new Rect();
        rectF.round(rect);
        return rect;
    }

    public void stopScan() {

    }
}

  

TestActivity:
package com.song.zxing;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import com.song.zxing.decode.BitmapDecodeHandler;
import com.song.zxing.decode.PreviewDecodeHandler;
import com.song.zxing.encode.QRCreator;
import com.song.zxing.ui.CameraView;
import com.song.zxing.ui.ScreenOverlay;
import com.song.zxing.util.BitmapUtil;
import com.song.zxing.util.Constant;

/**
 * Created by Administrator on 2015/12/16.
 */
public class TestActivity extends Activity {
    CameraView cameraView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        cameraView = (CameraView) findViewById(R.id.cameraView);
        final ScreenOverlay overlay = (ScreenOverlay) findViewById(R.id.overlay);
        cameraView.setInitListener(new CameraView.InitListener() {
            @Override
            public void initSuccess() {
                cameraView.setPreviewCallback(new PreviewDecodeHandler(overlay.getPreviewRect(), handler));
            }
        });
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new BitmapDecodeHandler().start(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/fuck.png"), handler);
            }
        });
        findViewById(R.id.btn_createQr).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = new QRCreator().createQRImage("this is a test string", 250, 250, BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
//                Bitmap bitmap = new QRCreator().createQRImage("this is a test string", 250, 250, null);
                BitmapUtil.write2File(bitmap, Environment.getExternalStorageDirectory() + "/fuck.png");
                App.toast("create complete!");
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == Constant.VALUE_DECODE_SUCCESS) {
                App.toast((String) msg.obj);
                cameraView.setPreviewCallback(null);// stop decode
            } else if (msg.what == Constant.VALUE_DECODE_FAIL) {
                App.toast("decode Fail");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraView.release();
        cameraView = null;
    }
}

  详细代码见:http://download.csdn.net/detail/hesongxing/9365515

注:工程代码使用Android studio 开发。

时间: 2024-12-25 07:52:54

Android zxing 解析二维码,生成二维码极简demo的相关文章

Android二维码开源项目zxing用例简化和生成二维码、条形码

上一篇讲到:Android二维码开源项目zxing编译,编译出来后有一个自带的测试程序:CaptureActivity比较复杂,我只要是把一些不用的东西去掉,用看起来更方便,二维码和条形码的流行性自不必说了. 自带的例子,目录结构如下: 修改后的程序目录结构,去掉了很多功能,如果分享.设置等. 先上效果图          扫描ZXing生成的条形码和二维码结果 扫描界面 扫描商品的条码 整个程序只修改了以下两个类,其它都是直接从原来的Demo中复制出来的 生成二维码的代码 /** * 生成二维

二维码生成,二维码中嵌套图片,文字生成图片

package com.fh.util; import java.awt.BasicStroke;import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream; import javax.

iOS中 扫描二维码/生成二维码详解 韩俊强的博客

最近大家总是问我有没有关于二维码的demo,为了满足大家的需求,特此研究了一番,希望能帮到大家! 每日更新关注:http://weibo.com/hanjunqiang  新浪微博 指示根视图: self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[SecondViewController new]]; 每日更新关注:http://weibo.com/hanjunqi

HTML5实现扫描识别二维码/生成二维码

扫描识别二维码 思路: 1. 操作摄像头,获取图片.HTML5 WEBRTC的navigator.getUserMedia方法去实时获取摄像头资源. 2. 利用canvas使用相关算法分析图片识别图片得出结果,可用jquery.qrcode分析二维码 .(技术点:getImageData) 局限性: 移动平台支持getUserMedia/Stream API的浏览器比较少,支持列表http://caniuse.com/#feat=stream (目前没发现有IOS是支持的) 代码实现: 感谢gi

&quot;iOS push全方位解析(三)【译文】&quot;——一个极简的demo,并测试一下push

这是一篇来自raywenderlich的教程,内容翔实!结构简单透彻.讲解循序渐进.文章质量上乘!是一篇难的的博文!使用半瓶的英语水平翻译了一下: 1. push的概述 2. 生成push证书,生成Provisioning Profile 3. 一个极简的demo,并测试一下push.(本博文) 这里查看原文 一个极简的demo 到目前为止,上面还不是做的还不够让人兴奋,但是那些准备工作还是很有必要的.本教程像你详细展示了如何生成证书,因为每天都会用到证书,而且没有证书push就不好.刚才你刚搞

Android 开发中使用到二维码生成和解析

二维码生成 二维码解析 在项目的开发中, 使用二维码作为数据传递 交换 已经是常态了! 在这我也讲讲自己在项目开发中使用到的二维码. 生成二维码的开发流程 1 应用google 给我们提供的zxing.jar (建议官网下载) 2 使用zxing.jar 的MultiFormatWriter 类 生成一张二维码图片 核心代码块 /** * 方法说明:生成无图片二维码 */ @SuppressWarnings("unused") private Bitmap createTwoCode(

Android -- 采用zxing生成二维码

首先在grandle里面添加zxing的库引用 compile 'com.google.zxing:core:3.1.0' 生成二维码静态类,返回一张二维码的Bitmap public class QrCodeUtil { // 生成QR图 public static Bitmap getQrCodeImage(int QR_WIDTH, int QR_HEIGHT, String text) throws WriterException { try { // 需要引入core包 QRCodeW

【VB.NET】利用 ZXing.Net 生成二维码(支持自定义LOGO)

ZXing .NET 的项目主页https://zxingnet.codeplex.com/ 代码基本上抄袭自下面两篇文章 XDhttp://www.cnblogs.com/tianma3798/p/5426869.htmlhttp://www.cnblogs.com/tianma3798/p/5426880.html 仅作参数优化,更加实用和简便一点 Shared Function MakeQR(ByVal qrtext As String, Optional ByVal width As I

利用zxing生成二维码

使用zxing类库可以很容易生成二维码QRCode,主要代码如下: private Bitmap createQRCode(String str,int width,int height) { Bitmap bmp=null; if(str.equals(""))return null; try { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map<EncodeHintType, Object&g