Crop 選擇相簿圖片並手動裁切
阿新 • • 發佈:2019-02-08
public classUtilsBitmap{ /** * 讀取一個縮放後的圖片,限定圖片大小,避免OOM * @paramuri圖片uri,支援“file://”、“content://” * @parammaxWidth最大允許寬度 * @parammaxHeight最大允許高度 * @return返回一個縮放後的Bitmap,失敗則返回null */ public staticBitmapdecodeUri(Context context,Uri uri,intmaxWidth,intmaxHeight){ BitmapFactory.Options options=newBitmapFactory.Options(); options.inJustDecodeBounds=true; //只讀取圖片尺寸 resolveUri(context,uri,options); //計算實際縮放比例 intscale=1; for(inti=0;i<Integer.MAX_VALUE;i++){ if((options.outWidth/scale>maxWidth&&options.outWidth/scale>maxWidth*1.4)|| (options.outHeight/scale>maxHeight&&options.outHeight/scale>maxHeight*1.4)){ scale++; }else{ break; } } options.inSampleSize=scale; options.inJustDecodeBounds=false;//讀取圖片內容 options.inPreferredConfig=Bitmap.Config.RGB_565;//根據情況進行修改 Bitmap bitmap=null; try{ bitmap=resolveUriForBitmap(context,uri,options); }catch(Throwable e){ e.printStackTrace(); } returnbitmap; } private static voidresolveUri(Context context,Uri uri,BitmapFactory.Options options){ if(uri==null){ return; } String scheme=uri.getScheme(); if(ContentResolver.SCHEME_CONTENT.equals(scheme)|| ContentResolver.SCHEME_FILE.equals(scheme)){ InputStream stream=null; try{ stream=context.getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(stream,null,options); }catch(Exception e){ Log.w("resolveUri","Unable to open content: "+uri,e); }finally{ if(stream!=null){ try{ stream.close(); }catch(IOException e){ Log.w("resolveUri","Unable to close content: "+uri,e); } } } }else if(ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)){ Log.w("resolveUri","Unable to close content: "+uri); }else{ Log.w("resolveUri","Unable to close content: "+uri); } } private staticBitmapresolveUriForBitmap(Context context,Uri uri,BitmapFactory.Options options){ if(uri==null){ return null; } Bitmap bitmap=null; String scheme=uri.getScheme(); if(ContentResolver.SCHEME_CONTENT.equals(scheme)|| ContentResolver.SCHEME_FILE.equals(scheme)){ InputStream stream=null; try{ stream=context.getContentResolver().openInputStream(uri); bitmap=BitmapFactory.decodeStream(stream,null,options); }catch(Exception e){ Log.w("resolveUriForBitmap","Unable to open content: "+uri,e); }finally{ if(stream!=null){ try{ stream.close(); }catch(IOException e){ Log.w("resolveUriForBitmap","Unable to close content: "+uri,e); } } } }else if(ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)){ Log.w("resolveUriForBitmap","Unable to close content: "+uri); }else{ Log.w("resolveUriForBitmap","Unable to close content: "+uri); } returnbitmap; } }