Android以最省內存的方式讀取本地資源的方法
方法一: /** * 獲取本地圖片並指定高度和寬度 */ public static Bitmap getNativeImage(String imagePath) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 獲取這個圖片的寬和高 Bitmap myBitmap = BitmapFactory.decodeFile(imagePath, options); //此時返回myBitmap為空 //計算縮放比 int be = (int)(options.outHeight / (float)200); int ys = options.outHeight % 200;//求餘數 float fe = ys / (float)200; if (fe >= 0.5) be = be + 1; if (be <= 0) be = 1; options.inSampleSize = be; //重新讀入圖片,注意這次要把options.inJustDecodeBounds 設為 false options.inJustDecodeBounds = false; myBitmap = BitmapFactory.decodeFile(imagePath, options); return myBitmap; } 方法二: /** * 以最省內存的方式讀取本地資源的圖片 * @param context * @param resId * @return */ public static Bitmap readBitMap(Context context, int resId) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //獲取資源圖片 InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); } 方法三: /** * 以最省內存的方式讀取本地資源的圖片 或者SDCard中的圖片 * @param imagePath * 圖片在SDCard中的路徑 * @return */ public static Bitmap getSDCardImg(String imagePath) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //獲取資源圖片 return BitmapFactory.decodeFile(imagePath, opt); }
最後更新:2017-04-02 16:48:11