Android 使用Bitmap将自身保存为文件,BitmapFactory从File中解析图片并防止OOM
1、使用Bitmap将自身保存为文件
public boolean saveBitmapAsFile(String name, Bitmap bitmap) { File saveFile = new File(cacheDirectory, name); boolean saved = false; FileOutputStream os = null; try { Log.d("FileCache", "Saving File To Cache " + saveFile.getPath()); os = new FileOutputStream(saveFile); bitmap.compress(CompressFormat.PNG, 100, os); os.flush(); os.close(); saved = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return saved; }
2、BitmapFactory从File中解析图片并防止OOM
/** 获得与需要的比例最接近的比例 */ static int calculateInSampleSize(BitmapFactory.Options bitmapOptions, int reqWidth, int reqHeight) { final int height = bitmapOptions.outHeight; final int width = bitmapOptions.outWidth; int sampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); sampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return sampleSize; } public static Bitmap decodeImage(String filePath) { /** Decode image size */ BitmapFactory.Options o = new BitmapFactory.Options(); /** 只取宽高防止oom */ o.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, o); int scale=calculateInSampleSize(o, displayStats.maxItemWidthHeight, displayStats.maxItemWidthHeight); BitmapFactory.Options options=new BitmapFactory.Options(); /** Decode with inSampleSize,比直接算出options中的使用更少的内存*/ options.inSampleSize=scale; /** 内存不足的时候可被擦除 */ options.inPurgeable = true; /** 深拷贝 */ options.inInputShareable = true; synchronized (DDGControlVar.DECODE_LOCK) { Bitmap result = BitmapFactory.decodeFile(filePath, options); return result; } }