网站建设算什么服务类型网网站建设与设计

当前位置: 首页 > news >正文

网站建设算什么服务类型,网网站建设与设计,洛阳建设厅网站,wordpress分类规则二维码介绍 zxing项目是谷歌推出的用来识别多种格式条形码的开源项目#xff0c;项目地址为https://github.com/zxing/zxing#xff0c;zxing有多个人在维护#xff0c;覆盖主流编程语言#xff0c;也是目前还在维护的较受欢迎的二维码扫描开源项目之一。 zxing的项目很庞… 二维码介绍 zxing项目是谷歌推出的用来识别多种格式条形码的开源项目项目地址为https://github.com/zxing/zxingzxing有多个人在维护覆盖主流编程语言也是目前还在维护的较受欢迎的二维码扫描开源项目之一。 zxing的项目很庞大主要的核心代码在core文件夹里面也可以单独下载由这个文件夹打包而成的jar包具体地址在http://mvnrepository.com/artifact/com.google.zxing/core直接下载jar包也省去了通过maven编译的麻烦如果喜欢折腾的可以从https://github.com/zxing/zxing/wiki/Getting-Started-Developing获取帮助文档。 zxing基本使用 官方提供了zxing在Android机子上的使用例子https://github.com/zxing/zxing/tree/master/android作为官方的例子zxing-android考虑了各种各样的情况包括多种解析格式、解析得到的结果分类、长时间无活动自动销毁机制等。有时候我们需要根据自己的情况定制使用需求因此会精简官方给的例子。在项目中我们仅仅用来实现扫描二维码和识别图片二维码两个功能。为了实现高精度的二维码识别在zxing原有项目的基础上本文做了大量改进使得二维码识别的效率有所提升。先来看看工程的项目结构。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21. ├── QrCodeActivity.java ├── camera │   ├── AutoFocusCallback.java │   ├── CameraConfigurationManager.java │   ├── CameraManager.java │   └── PreviewCallback.java ├── decode │   ├── CaptureActivityHandler.java │   ├── DecodeHandler.java │   ├── DecodeImageCallback.java │   ├── DecodeImageThread.java │   ├── DecodeManager.java │   ├── DecodeThread.java │   ├── FinishListener.java │   └── InactivityTimer.java ├── utils │   ├── QrUtils.java │   └── ScreenUtils.java └── view└── QrCodeFinderView.java源码比较简单这里不做过多地讲解大部分方法都有注释。主要分为几大块 camera 主要实现相机的配置和管理相机自动聚焦功能以及相机成像回调通过byte[]数组返回实际的数据。 decode 图片解析相关类。通过相机扫描二维码和解析图片使用两套逻辑。前者对实时性要求比较高后者对解析结果要求较高因此采用不同的配置。相机扫描主要在DecodeHandler里通过串行的方式解析图片识别主要通过线程DecodeImageThread异步调用返回回调的结果。FinishListener和InactivityTimer用来控制长时间无活动时自动销毁创建的Activity避免耗电。 扫描精度问题 使用过zxing自带的二维码扫描程序来识别二维码的童鞋应该知道zxing二维码的扫描程序很慢而且有可能扫不出来。zxing在配置相机参数和二维码扫描程序参数的时候配置都比较保守兼顾了低端手机并且兼顾了多种条形码的识别。如果说仅仅是拿zxing项目来扫描和识别二维码的话完全可以对项目中的一些配置做精简并针对二维码的识别做优化。 PlanarYUVLuminanceSource 官方的解码程序主要是下边这段代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21private void decode(byte[] data, int width, int height) {long start System.currentTimeMillis();Result rawResult null;// 构造基于平面的YUV亮度源即包含二维码区域的数据源PlanarYUVLuminanceSource source activity.getCameraManager().buildLuminanceSource(data, width, height);if (source ! null) {// 构造二值图像比特流使用HybridBinarizer算法解析数据源BinaryBitmap bitmap new BinaryBitmap(new HybridBinarizer(source));try {// 采用MultiFormatReader解析图像可以解析多种数据格式rawResult multiFormatReader.decodeWithState(bitmap);} catch (ReaderException re) {// continue} finally {multiFormatReader.reset();}}···// Hanlder处理解析失败或成功的结果··· }再来看看YUV亮度源是怎么构造的在CameraManager里首先获取预览图像的聚焦框矩形getFramingRect()这个聚焦框的矩形大小是根据屏幕的宽高值来做计算的官方定义了最小和最大的聚焦框大小分别是240*240和1200*675即最多的聚焦框大小为屏幕宽高的5/8。获取屏幕的聚焦框大小后还需要做从屏幕分辨率到相机分辨率的转换才能得到预览聚焦框的大小这个转换在getFramingRectInPreview()里完成。这样便完成了亮度源的构造。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95private static final int MIN_FRAME_WIDTH 240; private static final int MIN_FRAME_HEIGHT 240; private static final int MAX_FRAME_WIDTH 1200; // 58 * 1920 private static final int MAX_FRAME_HEIGHT 675; // 58 * 1080/*** A factory method to build the appropriate LuminanceSource object based on the format of the preview buffers, as* described by Camera.Parameters.** param data A preview frame.* param width The width of the image.* param height The height of the image.* return A PlanarYUVLuminanceSource instance./ public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {// 取得预览框内的矩形Rect rect getFramingRectInPreview();if (rect null) {return null;}// Go ahead and assume its YUV rather than die.return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, rect.width(), rect.height(),false); }/** Like {link #getFramingRect} but coordinates are in terms of the preview frame, not UI / screen.** return {link Rect} expressing barcode scan area in terms of the preview size*/ public synchronized Rect getFramingRectInPreview() {if (framingRectInPreview null) {Rect framingRect getFramingRect();if (framingRect null) {return null;}// 获取相机分辨率和屏幕分辨率Rect rect new Rect(framingRect);Point cameraResolution configManager.getCameraResolution();Point screenResolution configManager.getScreenResolution();if (cameraResolution null || screenResolution null) {// Called early, before init even finishedreturn null;}// 根据相机分辨率和屏幕分辨率的比例对屏幕中央聚焦框进行调整rect.left rect.left * cameraResolution.x / screenResolution.x;rect.right rect.right * cameraResolution.x / screenResolution.x;rect.top rect.top * cameraResolution.y / screenResolution.y;rect.bottom rect.bottom * cameraResolution.y / screenResolution.y;framingRectInPreview rect;}return framingRectInPreview; }/*** Calculates the framing rect which the UI should draw to show the user where to place the barcode. This target* helps with alignment as well as forces the user to hold the device far enough away to ensure the image will be in* focus.** return The rectangle to draw on screen in window coordinates.*/ public synchronized Rect getFramingRect() {if (framingRect null) {if (camera null) {return null;}// 获取屏幕的尺寸像素Point screenResolution configManager.getScreenResolution();if (screenResolution null) {// Called early, before init even finishedreturn null;}// 根据屏幕的宽高找到最合适的矩形框宽高值int width findDesiredDimensionInRange(screenResolution.x, MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);int height findDesiredDimensionInRange(screenResolution.y, MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);// 取屏幕中间的宽为width高为height的矩形框int leftOffset (screenResolution.x - width) / 2;int topOffset (screenResolution.y - height) / 2;framingRect new Rect(leftOffset, topOffset, leftOffset width, topOffset height);Log.d(TAG, Calculated framing rect: framingRect);}return framingRect; }private static int findDesiredDimensionInRange(int resolution, int hardMin, int hardMax) {int dim 5 * resolution / 8; // Target 58 of each dimensionif (dim hardMin) {return hardMin;}if (dim hardMax) {return hardMax;}return dim; }这段代码并没有什么问题也完全符合逻辑。但为什么在扫描的时候这么难扫到二维码呢原因在于官方为了减少解码的数据提高解码效率和速度采用了裁剪无用区域的方式。这样会带来一定的问题整个二维码数据需要完全放到聚焦框里才有可能被识别并且在buildLuminanceSource(byte[],int,int)这个方法签名中传入的byte数组便是图像的数据并没有因为裁剪而使数据量减小而是采用了取这个数组中的部分数据来达到裁剪的目的。对于目前CPU性能过剩的大多数智能手机来说这种裁剪显得没有必要。如果把解码数据换成采用全幅图像数据这样在识别的过程中便不再拘束于聚焦框也使得二维码数据可以铺满整个屏幕。这样用户在使用程序来扫描二维码时尽管不完全对准聚焦框也可以识别出来。这属于一种策略上的让步给用户造成了错觉但提高了识别的精度。 解决办法很简单就是不仅仅使用聚焦框里的图像数据而是采用全幅图像的数据。 1 2 3 4public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {// 直接返回整幅图像的数据而不计算聚焦框大小。return new PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false); }DecodeHintType 在使用zxing解析二维码时允许事先进行相关配置这个文件通过MapDecodeHintType, ?键值对来保存然后使用方法public void setHints(MapDecodeHintType,? hints)来设置到相应的解码器中。DecodeHintType是一个枚举类其中有几个重要的枚举值 POSSIBLE_FORMATS(List.class) 用于列举支持的解析格式一共有17种在com.google.zxing.BarcodeFormat里定义。官方默认支持所有的格式。 TRY_HARDER(Void.class) 是否使用HARDER模式来解析数据如果启用则会花费更多的时间去解析二维码对精度有优化对速度则没有。 CHARACTER_SET(String.class) 解析的字符集。这个对解析也比较关键最好定义需要解析数据对应的字符集。 如果项目仅仅用来解析二维码完全没必要支持所有的格式也没有必要使用MultiFormatReader来解析。所以在配置的过程中我移除了所有与二维码不相关的代码。直接使用QRCodeReader类来解析字符集采用utf-8使用Harder模式并且把可能的解析格式只定义为BarcodeFormat.QR_CODE这对于直接二维码扫描解析无疑是帮助最大的。 1 2 3 4 5 6 7 8 9private final MapDecodeHintType, Object mHints; DecodeHandler(QrCodeActivity activity) {this.mActivity activity;mQrCodeReader new QRCodeReader();mHints new Hashtable();mHints.put(DecodeHintType.CHARACTER_SET, utf-8);mHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);mHints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE); }二维码图像识别精度探究 图像/像素编码格式 Android相机预览的时候支持几种不同的格式从图像的角度ImageFormat来说有NV16、NV21、YUY2、YV12、RGB_565和JPEG从像素的角度PixelFormat来说有YUV422SP、YUV420SP、YUV422I、YUV420P、RGB565和JPEG它们之间的对应关系可以从Camera.Parameters.cameraFormatForPixelFormat(int)方法中得到。 1 2 3 4 5 6 7 8 9 10 11private String cameraFormatForPixelFormat(int pixel_format) {switch(pixel_format) {case ImageFormat.NV16: return PIXEL_FORMAT_YUV422SP;case ImageFormat.NV21: return PIXEL_FORMAT_YUV420SP;case ImageFormat.YUY2: return PIXEL_FORMAT_YUV422I;case ImageFormat.YV12: return PIXEL_FORMAT_YUV420P;case ImageFormat.RGB_565: return PIXEL_FORMAT_RGB565;case ImageFormat.JPEG: return PIXEL_FORMAT_JPEG;default: return null;} }目前大部分Android手机摄像头设置的默认格式是yuv420sp其原理可参考文章《图文详解YUV420数据格式》。编码成YUV的所有像素格式里yuv420sp占用的空间是最小的。既然如此zxing当然会考虑到这种情况。因此针对YUV编码的数据有PlanarYUVLuminanceSource这个类去处理而针对RGB编码的数据则使用RGBLuminanceSource去处理。在下节介绍的图像识别算法中我们可以知道大部分二维码的识别都是基于二值化的方法在色域的处理上YUV的二值化效果要优于RGB并且RGB图像在处理中不支持旋转。因此一种优化的思路是讲所有ARGB编码的图像转换成YUV编码再使用PlanarYUVLuminanceSource去处理生成的结果。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56/*** RGB转YUV420sp** param yuv420sp inputWidth * inputHeight * 3 / 2* param argb inputWidth * inputHeight* param width image width* param height image height*/ private static void encodeYUV420SP(byte[] yuv420sp, int[] argb, int width, int height) {// 帧图片的像素大小final int frameSize width * height;// —YUV数据—int Y, U, V;// Y的index从0开始int yIndex 0;// UV的index从frameSize开始int uvIndex frameSize;// —颜色数据—int R, G, B;int rgbIndex 0;// —循环所有像素点RGB转YUV—for (int j 0; j height; j) {for (int i 0; i width; i) {R (argb[rgbIndex] 0xff0000) 16;G (argb[rgbIndex] 0xff00) 8;B (argb[rgbIndex] 0xff);//rgbIndex;// well known RGB to YUV algorithmY ((66 * R 129 * G 25 * B 128) 8) 16;U ((-38 * R - 74 * G 112 * B 128) 8) 128;V ((112 * R - 94 * G - 18 * B 128) 8) 128;Y Math.max(0, Math.min(Y, 255));U Math.max(0, Math.min(U, 255));V Math.max(0, Math.min(V, 255));// NV21 has a plane of Y and interleaved planes of VU each sampled by a factor of 2// meaning for every 4 Y pixels there are 1 V and 1 U. Note the sampling is every other// pixel AND every other scan line.// —Y—yuv420spyIndex Y;// —UV—if ((j % 2 0) (i % 2 0)) {//yuv420spuvIndex V;//yuv420spuvIndex U;}}} }Android中读取一张图片一般是通过BitmapFactory.decodeFile(imgPath, options)这个方法去得到这张图片的Bitmap数据Bitmap是由ARGB值编码得到的因此如果需要转换成YUV还需要做一点小小的变换。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33private static byte[] yuvs; /*** 根据Bitmap的ARGB值生成YUV420SP数据。** param inputWidth image width* param inputHeight image height* param scaled bmp* return YUV420SP数组*/ public static byte[] getYUV420sp(int inputWidth, int inputHeight, Bitmap scaled) {int[] argb new int[inputWidth * inputHeight];scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);/*** 需要转换成偶数的像素点否则编码YUV420的时候有可能导致分配的空间大小不够而溢出。*/int requiredWidth inputWidth % 2 0 ? inputWidth : inputWidth 1;int requiredHeight inputHeight % 2 0 ? inputHeight : inputHeight 1;int byteLength requiredWidth * requiredHeight * 3 / 2;if (yuvs null || yuvs.length byteLength) {yuvs new byte[byteLength];} else {Arrays.fill(yuvs, (byte) 0);}encodeYUV420SP(yuvs, argb, inputWidth, inputHeight);scaled.recycle();return yuvs; }这里面有几个坑在方法里已经列出来了。首先如果每次都生成新的YUV数组不知道在扫一扫解码时要进行GC多少次。。。所以就采用了静态的数组变量来存储数据只有当当前的长宽乘积超过数组大小时才重新生成新的yuvs。其次如果鉴于YUV的特性长宽只能是偶数个像素点否则可能会造成数组溢出(不信可以尝试)。最后使用完了Bitmap要记得回收那玩意吃内存不是随便说说的。 二维码图像识别算法选择 二维码扫描精度和许多因素有关最关键的因素是扫描算法。目前在图形识别领域中较常用的二维码识别算法主要有两种分别是HybridBinarizer和GlobalHistogramBinarizer这两种算法都是基于二值化即将图片的色域变为黑白两个颜色然后提取图形中的二维码矩阵。实际上zxing中的HybridBinarizer继承自GlobalHistogramBinarizer并在此基础上做了功能性的改进。援引官方介绍 This Binarizer(GlobalHistogramBinarizer) implementation uses the old ZXing global histogram approach. It is suitable for low-end mobile devices which don’t have enough CPU or memory to use a local thresholding algorithm. However, because it picks a global black point, it cannot handle difficult shadows and gradients. Faster mobile devices and all desktop applications should probably use HybridBinarizer instead. This class(HybridBinarizer) implements a local thresholding algorithm, which while slower than the GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for high frequency images of barcodes with black data on white backgrounds. For this application, it does a much better job than a global blackpoint with severe shadows and gradients. However it tends to produce artifacts on lower frequency images and is therefore not a good general purpose binarizer for uses outside ZXing. This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers, and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already inherently local, and only fails for horizontal gradients. We can revisit that problem later, but for now it was not a win to use local blocks for 1D. ··· GlobalHistogramBinarizer算法适合于低端的设备对手机的CPU和内存要求不高。但它选择了全部的黑点来计算因此无法处理阴影和渐变这两种情况。HybridBinarizer算法在执行效率上要慢于GlobalHistogramBinarizer算法但识别相对更有效。它专门为以白色为背景的连续黑色块二维码图像解析而设计也更适合用来解析具有严重阴影和渐变的二维码图像。 网上对这两种算法的解析并不多目前仅找到一篇文章详解了GlobalHistogramBinarizer算法详见http://kuangjianwei.blog.163.com/blog/static/190088953201361015055110/。有时间再看一下相关源码。 zxing项目官方默认使用的是HybridBinarizer二值化方法。在实际的测试中和官方的介绍大致一样。然而目前的大部分二维码都是黑色二维码白色背景的。不管是二维码扫描还是二维码图像识别使用GlobalHistogramBinarizer算法的效果要稍微比HybridBinarizer好一些识别的速度更快对低分辨的图像识别精度更高。 除了这两种算法我相信在图像识别领域肯定还有更好的算法存在目前受限于知识水平对二值化算法这一块还比较陌生期待以后能够深入理解并改进目前的开源算法(^__^)…… 图像大小对识别精度的影响 这点是测试中无意发现的。现在的手机摄像头拍照出现的照片像素都很高动不动就1200W像素1600W像素甚至是2000W都不稀奇但照片的成像质量不一定高。将一张高分辨率的图片按原分辨率导入Android手机很容易产生OOM。我们来计算一下导入一张1200W像素的图片需要的内存假设图片是4000px*3000px如果导入的图片采用ARGB_8888编码形式则每个像素需要占用4个Bytes(分别存储ARGB值)来存储则需要4000*30004bytes45.776MB的内存这在有限的移动资源里显然是不能忍受的。 通过上一节对图像算法的简单研究在GlobalHistogramBinarizer中是从图像中均匀取5行覆盖整个图像高度每行取中间五分之四作为样本以灰度值为X轴每个灰度值的像素个数为Y轴建立一个直方图从直方图中取点数最多的一个灰度值然后再去给其他的灰度值进行分数计算按照点数乘以与最多点数灰度值的距离的平方来进行打分选分数最高的一个灰度值。接下来在这两个灰度值中间选取一个区分界限取的原则是尽量靠近中间并且要点数越少越好。界限有了以后就容易了与整幅图像的每个点进行比较如果灰度值比界限小的就是黑在新的矩阵中将该点置1其余的就是白为0。摘自zxing源码分析——QR码部分 根据算法的实现可以知道图像的分辨率对二维码的取值是有影响的。并不是图像的分辨率越高就越容易取到二维码。高分辨率的图像对Android的内存资源占用也很可怕。所以在测试的过程中我尝试将图片压缩成不同大小分辨率然后再进行图片的二维码识别。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51/** 根据给定的宽度和高度动态计算图片压缩比率* * param options Bitmap配置文件* param reqWidth 需要压缩到的宽度* param reqHeight 需要压缩到的高度* return 压缩比*/ public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {// Raw height and width of imagefinal int height options.outHeight;final int width options.outWidth;int inSampleSize 1;if (height reqHeight || width reqWidth) {final int halfHeight height / 2;final int halfWidth width / 2;// Calculate the largest inSampleSize value that is a power of 2 and keeps both// height and width larger than the requested height and width.while ((halfHeight / inSampleSize) reqHeight (halfWidth / inSampleSize) reqWidth) {inSampleSize * 2;}}return inSampleSize; }/*** 将图片根据压缩比压缩成固定宽高的Bitmap实际解析的图片大小可能和#reqWidth、#reqHeight不一样。* * param imgPath 图片地址* param reqWidth 需要压缩到的宽度* param reqHeight 需要压缩到的高度* return Bitmap*/ public static Bitmap decodeSampledBitmapFromFile(String imgPath, int reqWidth, int reqHeight) {// First decode with inJustDecodeBoundstrue to check dimensionsfinal BitmapFactory.Options options new BitmapFactory.Options();options.inJustDecodeBounds true;BitmapFactory.decodeFile(imgPath, options);// Calculate inSampleSizeoptions.inSampleSize calculateInSampleSize(options, reqWidth, reqHeight);// Decode bitmap with inSampleSize setoptions.inJustDecodeBounds false;return BitmapFactory.decodeFile(imgPath, options); }Android图片优化需要通过在解析图片的时候设置BitmapFactory.Options.inSampleSize的值根据比例压缩图片大小。在进行图片二维码解析的线程中通过设置不同的图片大小来测试二维码的识别率。这个测试过程我忘记保存了只记得测试了压缩成最大宽高值为2048、1024、512、256和128像素的包含二维码的图片但实际的测试结果是当MAX_PICTUREPIXEL256的时候识别率最高。 此结论不具备理论支持有兴趣的童鞋可以自己动手尝试。^^ 相机预览倍数设置及聚焦时间调整 如果使用zxing默认的相机配置会发现需要离二维码很近才能够识别出来但这样会带来一个问题——聚焦困难。解决办法就是调整相机预览倍数以及减小相机聚焦的时间。 通过测试可以发现每个手机的最大放大倍数几乎是不一样的这可能和摄像头的型号有关。如果设置成一个固定的值那可能会产生在某些手机上过度放大某些手机上放大的倍数不够。索性相机的参数设定里给我们提供了最大的放大倍数值通过取放大倍数值的N分之一作为当前的放大倍数就完美地解决了手机的适配问题。 1 2 3 4 5 6// 需要判断摄像头是否支持缩放 Parameters parameters camera.getParameters(); if (parameters.isZoomSupported()) {// 设置成最大倍数的1/10基本符合远近需求parameters.setZoom(parameters.getMaxZoom() / 10); }zxing默认的相机聚焦时间是2s可以根据扫描的视觉适当调整。聚焦时间的调整也很简单在AutoFocusCallback这个类里调整AUTO_FOCUS_INTERVAL_MS这个值就可以了。 二维码扫描视觉调整 二维码扫描视觉的绘制在ViewfinderView.java完成官方是继承了View然后在onDraw()方法中实现了视图的绘制。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72Override public void onDraw(Canvas canvas) {if (cameraManager null) {return; // not ready yet, early draw before done configuring}Rect frame cameraManager.getFramingRect();Rect previewFrame cameraManager.getFramingRectInPreview();if (frame null || previewFrame null) {return;}int width canvas.getWidth();int height canvas.getHeight();// 绘制聚焦框外的暗色透明层paint.setColor(resultBitmap ! null ? resultColor : maskColor);canvas.drawRect(0, 0, width, frame.top, paint);canvas.drawRect(0, frame.top, frame.left, frame.bottom 1, paint);canvas.drawRect(frame.right 1, frame.top, width, frame.bottom 1, paint);canvas.drawRect(0, frame.bottom 1, width, height, paint);if (resultBitmap ! null) {// 如果扫描结果不为空则把扫描的结果填充到聚焦框中paint.setAlpha(CURRENT_POINT_OPACITY);canvas.drawBitmap(resultBitmap, null, frame, paint);} else {// 画一根红色的激光线表示二维码解码正在进行paint.setColor(laserColor);paint.setAlpha(SCANNER_ALPHA[scannerAlpha]);scannerAlpha (scannerAlpha 1) % SCANNER_ALPHA.length;int middle frame.height() / 2 frame.top;canvas.drawRect(frame.left 2, middle - 1, frame.right - 1, middle 2, paint);float scaleX frame.width() / (float) previewFrame.width();float scaleY frame.height() / (float) previewFrame.height();ListResultPoint currentPossible possibleResultPoints;ListResultPoint currentLast lastPossibleResultPoints;int frameLeft frame.left;int frameTop frame.top;// 绘制解析过程中可能扫描到的关键点使用黄色小圆点表示if (currentPossible.isEmpty()) {lastPossibleResultPoints null;} else {possibleResultPoints new ArrayList(5);lastPossibleResultPoints currentPossible;paint.setAlpha(CURRENT_POINT_OPACITY);paint.setColor(resultPointColor);synchronized (currentPossible) {for (ResultPoint point : currentPossible) {canvas.drawCircle(frameLeft (int) (point.getX() * scaleX),frameTop (int) (point.getY() * scaleY), POINT_SIZE, paint);}}}if (currentLast ! null) {paint.setAlpha(CURRENT_POINT_OPACITY / 2);paint.setColor(resultPointColor);synchronized (currentLast) {float radius POINT_SIZE / 2.0f;for (ResultPoint point : currentLast) {canvas.drawCircle(frameLeft (int) (point.getX() * scaleX),frameTop (int) (point.getY() * scaleY), radius, paint);}}}// 重绘聚焦框里的内容不需要重绘整个界面。postInvalidateDelayed(ANIMATION_DELAY, frame.left - POINT_SIZE, frame.top - POINT_SIZE,frame.right POINT_SIZE, frame.bottom POINT_SIZE);} }我给它做了一点小改变效果差不多代码更简洁一些。由于代码中我不是根据屏幕的宽高动态计算聚焦框的大小因此这里省去了从CameraManager获取FramingRect和FramingRectInPreview这两个矩形的过程。我在聚焦框外加了四个角目前大部分二维码产品基本都是这么设计的吧当然也可以使用图片来代替。总之视觉定制是因人而异这里不做过多介绍。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102Override public void onDraw(Canvas canvas) {if (isInEditMode()) {return;}Rect frame mFrameRect;if (frame null) {return;}int width canvas.getWidth();int height canvas.getHeight();// 绘制焦点框外边的暗色背景mPaint.setColor(mMaskColor);canvas.drawRect(0, 0, width, frame.top, mPaint);canvas.drawRect(0, frame.top, frame.left, frame.bottom 1, mPaint);canvas.drawRect(frame.right 1, frame.top, width, frame.bottom 1, mPaint);canvas.drawRect(0, frame.bottom 1, width, height, mPaint);drawFocusRect(canvas, frame);drawAngle(canvas, frame);drawText(canvas, frame);drawLaser(canvas, frame);// Request another update at the animation interval, but only repaint the laser line,// not the entire viewfinder mask.postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); }/*** 画聚焦框白色的* * param canvas* param rect/ private void drawFocusRect(Canvas canvas, Rect rect) {// 绘制焦点框黑色mPaint.setColor(mFrameColor);// 上canvas.drawRect(rect.left mAngleLength, rect.top, rect.right - mAngleLength, rect.top mFocusThick, mPaint);// 左canvas.drawRect(rect.left, rect.top mAngleLength, rect.left mFocusThick, rect.bottom - mAngleLength,mPaint);// 右canvas.drawRect(rect.right - mFocusThick, rect.top mAngleLength, rect.right, rect.bottom - mAngleLength,mPaint);// 下canvas.drawRect(rect.left mAngleLength, rect.bottom - mFocusThick, rect.right - mAngleLength, rect.bottom,mPaint); }/** 画粉色的四个角* * param canvas* param rect*/ private void drawAngle(Canvas canvas, Rect rect) {mPaint.setColor(mLaserColor);mPaint.setAlpha(OPAQUE);mPaint.setStyle(Paint.Style.FILL);mPaint.setStrokeWidth(mAngleThick);int left rect.left;int top rect.top;int right rect.right;int bottom rect.bottom;// 左上角canvas.drawRect(left, top, left mAngleLength, top mAngleThick, mPaint);canvas.drawRect(left, top, left mAngleThick, top mAngleLength, mPaint);// 右上角canvas.drawRect(right - mAngleLength, top, right, top mAngleThick, mPaint);canvas.drawRect(right - mAngleThick, top, right, top mAngleLength, mPaint);// 左下角canvas.drawRect(left, bottom - mAngleLength, left mAngleThick, bottom, mPaint);canvas.drawRect(left, bottom - mAngleThick, left mAngleLength, bottom, mPaint);// 右下角canvas.drawRect(right - mAngleLength, bottom - mAngleThick, right, bottom, mPaint);canvas.drawRect(right - mAngleThick, bottom - mAngleLength, right, bottom, mPaint); }private void drawText(Canvas canvas, Rect rect) {int margin 40;mPaint.setColor(mTextColor);mPaint.setTextSize(getResources().getDimension(R.dimen.text_size_13sp));String text getResources().getString(R.string.qr_code_auto_scan_notification);Paint.FontMetrics fontMetrics mPaint.getFontMetrics();float fontTotalHeight fontMetrics.bottom - fontMetrics.top;float offY fontTotalHeight / 2 - fontMetrics.bottom;float newY rect.bottom margin offY;float left (ScreenUtils.getScreenWidth(mContext) - mPaint.getTextSize() * text.length()) / 2;canvas.drawText(text, left, newY, mPaint); }private void drawLaser(Canvas canvas, Rect rect) {// 绘制焦点框内固定的一条扫描线红色mPaint.setColor(mLaserColor);mPaint.setAlpha(SCANNER_ALPHA[mScannerAlpha]);mScannerAlpha (mScannerAlpha 1) % SCANNER_ALPHA.length;int middle rect.height() / 2 rect.top;canvas.drawRect(rect.left 2, middle - 1, rect.right - 1, middle 2, mPaint);}总结 使用zxing进行二维码的编解码是非常方便的zxing的API覆盖了多种主流编程语言具有良好的扩展性和可定制性。文中进行了二维码基本功能介绍zxing项目基本使用方法zxing项目中目前存在的缺点及改进方案以及自己在进行zxing项目二次开发的摸索过程中总结出的提高二维码扫描的方法。文中还有许多不足的地方对源码的理解还不够深特别是二维码解析关键算法GlobalHistogramBinarizer和HybridBinarizer。这些算法需要投入额外的时间去理解对于目前以业务为导向的App开发来说还存在优化的空间期待将来有一天能像微信的二维码扫描一样快速精确。 转自http://iluhcm.com/2016/01/08/scan-qr-code-and-recognize-it-from-picture-fastly-using-zxing/