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 开发。