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;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM