zoukankan      html  css  js  c++  java
  • 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;
            }
        }
  • 相关阅读:
    Freezable 对象(WPF)
    排序算法
    属性,构造函数,枚举
    .net 4.0新特性CountDownEvent
    WPF的动画(1)基本动画
    MEF(Managed Extensibility Framework)学习笔记
    WPF依赖属性(续)(4)依赖属性与数据绑定
    [你必须知道的.NET] 第六回:深入浅出关键字base和this
    [你必须知道的.NET] 第三回:历史纠葛:特性和属性
    用命令行部分解决 CNNIC 证书问题
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/8351950.html
Copyright © 2011-2022 走看看