Android實現儲存圖片,長圖、長佈局(webView等)
阿新 • • 發佈:2018-11-07
最近開發遇到一個問題,分享的時候 需要分享一個佈局內容,但是要用圖片分享的格式,最開始思考感覺不可能實現,手機上很少有功能可以實現長圖儲存的,
可是經理說,髮長微博的時候就是自動儲存的長圖片,頓時傻眼了,人家是怎麼做的呢???
本已經放棄該功能,可這麼一說,又開始在網上找,並沒有很明確的找到答案,僥倖今天在群裡問了一下,就有一哥們說了,還給我程式碼,
太感謝了 ,我想肯定有人和我遇到同樣的問題,就分享一下吧。一起進步。
大神的程式碼,在此借用,希望能幫助到大家。
/** * view截圖,webview和scrollview(scrollview需要傳入子view)之類的view能夠擷取整個長度的bitmap, * 如果webview內容很多,view.draw(Canvas)方法會很耗時,在子程序中操作會有額外的問題,所以會暫時阻塞 * UI主執行緒,求方法~ */ public static Bitmap viewShot(final View view){ if (view == null) return null; view.setDrawingCacheEnabled(true); view.buildDrawingCache();int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(measureSpec, measureSpec); if (view.getMeasuredWidth()<=0 || view.getMeasuredHeight()<=0) { L.e("ImageUtils.viewShot size error"); return null; } Bitmap bm; try{ bm = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); }catch (OutOfMemoryError e){ System.gc(); try { bm = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); }catch (OutOfMemoryError ee){ L.e("ImageUtils.viewShot error", ee); return null; } } Canvas bigCanvas = new Canvas(bm); Paint paint = new Paint(); int iHeight = bm.getHeight(); bigCanvas.drawBitmap(bm, 0, iHeight, paint); view.draw(bigCanvas); return bm; } 上面是大神給的儲存轉成Bitmap的圖,儲存到手機還是要自己實現哦。 在此就給出儲存圖片的程式碼
/** * 儲存圖片到手機相簿,並通知相簿更新 * @param context * @param bmp 圖片bitmap * @return 返回圖片儲存的路徑,開發人員可以根據返回的路徑在手機裡面檢視,部分手機發送通知相簿並不會更新 */
public static String saveImageToGallery(Context context, Bitmap bmp) { // 首先儲存圖片 File appDir = new File(Environment.getExternalStorageDirectory(), "saveImage"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 最後通知相簿更新 String path = Environment.getExternalStorageDirectory() + "/
saveImage
/" + fileName; context.sendBroadcast(
new Intent(Intent.
ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.
parse(
"file://" + path)));
return Environment.
getExternalStorageDirectory() +
"/
saveImage/" + fileName;}