Android webview長按識別二維碼及儲存圖片到本地
新增所需要的依賴框架:
implementation 'cn.yipianfengye.android:zxing-library:2.2' implementation 'com.github.bumptech.glide:glide:4.1.1'
長按識別圖片是否為二維碼:
/** * 長按webview圖片 */ webView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { final WebView.HitTestResult htr = ((WebView) v).getHitTestResult();//獲取所點選的內容 if (htr.getType() == WebView.HitTestResult.IMAGE_TYPE //判斷被點選的型別為圖片 || htr.getType() == WebView.HitTestResult.IMAGE_ANCHOR_TYPE || htr.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) { imagePath = htr.getExtra(); analyzeBitmap(htr.getExtra(), new AnalyzeCallback() { @Override public void onAnalyzeSuccess(Bitmap mBitmap, final String result) { List<String> list = new ArrayList<>(); list.add("儲存圖片到本地"); list.add("識別圖中二維碼"); showDialog(list, result); } @Override public void onAnalyzeFailed() { List<String> list = new ArrayList<>(); list.add("儲存圖片到本地"); showDialog(list, ""); } }); } return false; } }); /** * 解析二維碼圖片工具類 */ public void analyzeBitmap(final String path, final AnalyzeCallback analyzeCallback) { Glide.with(getActivity()).load(path).into(new SimpleTarget<Drawable>() { @Override public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) { BitmapDrawable bd = (BitmapDrawable) resource; mBitmap = bd.getBitmap(); MultiFormatReader multiFormatReader = new MultiFormatReader(); // 解碼的引數 Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(2); // 可以解析的編碼型別 Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>(); if (decodeFormats == null || decodeFormats.isEmpty()) { decodeFormats = new Vector<BarcodeFormat>(); // 這裡設定可掃描的型別,我這裡選擇了都支援 decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS); decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS); decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS); } hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); // 設定繼續的字元編碼格式為UTF8 // hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); // 設定解析配置引數 multiFormatReader.setHints(hints); // 開始對影象資源解碼 Result rawResult = null; try { rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(mBitmap)))); } catch (Exception e) { e.printStackTrace(); } if (rawResult != null) { if (analyzeCallback != null) { analyzeCallback.onAnalyzeSuccess(mBitmap, rawResult.getText()); } } else { if (analyzeCallback != null) { analyzeCallback.onAnalyzeFailed(); } } } }); } /** * 解析二維碼結果 */ public interface AnalyzeCallback { void onAnalyzeSuccess(Bitmap mBitmap, String result); void onAnalyzeFailed(); }
附:儲存圖片到本地的方法:
private class SaveImage extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String result = ""; try { String sdcard = null; String sdStatus = Environment.getExternalStorageState(); if (sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 檢測sd卡是否可用 sdcard = Environment.getExternalStorageDirectory().getAbsolutePath(); } else { ToastUtil.show(getActivity(), "SD卡不可用"); } File file = new File(sdcard + "/Download"); if (!file.exists()) { file.mkdirs(); } file = new File(sdcard + "/Download/" + new Date().getTime() + ".jpg"); InputStream inputStream = null; URL url = new URL(imagePath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(20000); if (conn.getResponseCode() == 200) { inputStream = conn.getInputStream(); } byte[] buffer = new byte[4096]; int len = 0; FileOutputStream outStream = new FileOutputStream(file); while ((len = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } outStream.close(); result = "圖片已儲存至:" + file.getAbsolutePath(); } catch (Exception e) { result = "儲存失敗!" + e.getLocalizedMessage(); } return result; } @Override protected void onPostExecute(String result) { ToastUtil.show(getActivity(), result); } }
使用方法:
SaveImage saveImage = new SaveImage(); saveImage.execute();
注:Android 6.0以上需動態申請許可權:WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE,才能儲存圖片到本地。