前言:昨天寫了一篇博客記錄了一下ImageView長按實現圖片的保存,在生活中使用微信的時候會發現長按圖片,圖片中如果含有二維碼的話會彈出一個有“識別二維碼”的彈窗,也就是說有無二維碼彈出框是不一樣的。今天,趁着午休的時間在保存圖片demo的基礎上進行了一下修改,實現簡單的二維碼識別功能。
邏輯流程:用戶長按圖片—ImageView截圖—判斷有無二維碼—提示
關鍵代碼:
img = (ImageView) findViewById(R.id.qrcode); img.setDrawingCacheEnabled(true); img.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View view) { Bitmap bitmap = ((ImageView) view).getDrawingCache(); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] data = new int[width * height]; bitmap.getPixels(data, 0, width, 0, 0, width, height); RGBLuminanceSource source = new RGBLuminanceSource(width, height, data); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); Result re = null; try { re = reader.decode(bitmap1); } catch (NotFoundException e) { e.printStackTrace(); } catch (ChecksumException e) { e.printStackTrace(); } catch (FormatException e) { e.printStackTrace(); } if (re == null) { Toast.makeText(MainActivity.this,"沒有找到二維碼", Toast.LENGTH_SHORT).show(); } else { String text = re.getText(); Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show(); } return true; } });
需要注意的是在使用getDrawingCache之前必須要調用setDrawingCacheEnabled,除此之外識別二維碼是用的ZXing庫,需要提前引入
demo比較簡單,附上地址