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;
            }
        }
  • 相关阅读:
    iOS 9之适配ATS(转载)
    ios8 tableView设置滑动删除时 显示多个按钮
    PHP IDE phpstorm 快捷键
    ld: warning: directory not found for option 去掉警告的方法
    iOS 评论APP撰写评论
    集成IOS 环信SDK
    iOS Xcode7免证书真机调试
    iOS定时器
    配置安装CocoPods后进行 项目基本配置
    事务的概念
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/8351950.html
Copyright © 2011-2022 走看看