zoukankan      html  css  js  c++  java
  • android处理拍照旋转问题及带来的对内存占用的思考

    想必大家对android处理拍照并保存照片的应用场景已经再熟悉不过了,其中比较头疼的问题是像部分三星手机拍完照片后保存的图片是旋转90度后的图片(当然,如果横向拍照是没有问题的)。

    本篇文章目的不是简单解决旋转问题,而是通过这样的问题讨论下android内存占用(主要是图片)的问题。通过文章大家可以掌握如下知识:

    1. 如何解决上面提到的三星拍照问题
    2. 如何计算bitmap占用的内存大小
    3. 如何尽量避免OOM的出现

    解决旋转问题的方案可以是:当拍照完成并保存图片到某个路径(比如用file记录了图片路径)下以后,加载原始图片得到bitmap,再通过对其进行旋转生成新的bitmap,最后保存bitmap到file路径下来覆盖原始路径下的内容。
    显示代码如下(至于如果开启摄像机并拍照保存不在讨论范围):
    AlbumAcitivity.java 核心代码如下:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
            //扫描制定位置的文件
            String scanPath = file.getAbsolutePath();
            doRotateImageAndSave(scanPath);
        }
    }
    //通过img得到旋转rotate角度后的bitmap
    public static Bitmap rotateImage(Bitmap img,int rotate){
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        int width = img.getWidth();
        int height =img.getHeight();
        img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, false);
        return img;
    }
    //加载filePath下的图片,旋转并保存到filePath
    private void doRotateImageAndSaveStrategy1(String filePath){
        int rotate = readPictureDegree(filePath);//获取需要加载图片的旋转角度
        if(rotate == 0){
            return;
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            Bitmap destBitmap = rotateImage(bitmap, rotate);
            bitmap.recycle();
    
            //save to file
            FileUtil.saveImageToSDCard(destBitmap, 100, filePath);
            destBitmap.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
    private void doRotateImageAndSave(String filePath){
        doRotateImageAndSaveStrategy1(filePath);
    }
    /**
     * 读取照片exif信息中的旋转角度
     * @param path 照片路径
     * @return角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        ExifInterface exifInterface = null;
        try {
            exifInterface = new ExifInterface(path);
        } catch (IOException ex) {
        }
        if(exifInterface == null)
            return degree;
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                degree = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                degree = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                degree = 270;
                break;
        }
        return degree;
    }
    

    由于代码量不是很大,而且逻辑并不复在所以在这就一一解释每行代码的含义了。经过测试发现在调用到doRotateImageAndSave方法时内存占用直线上升,大概一下子增加了60~70MB。如果再加上整个应用之前占用的内存恐怕瞬时的内存压力还是很大的。
    至于出现占用这么大内存的原因,稍有经验的coder应该知道直接加载原图而不做任何处理显然是很危险的,如果摄像头的分辨率越高拍出的照片越大,在内存中解码出来后占用的内存越高。

    经过(三星S6 edge+)测试发现:拍出的照片分辨率是5312*2988的,那么这张图片解码后会占用多大内存呢?如下公式可以表示:
    占用内存大小 size = width * height * 颜色深度(depth)
    至于何为颜色深度大家自己百度或google吧,简单讲就是图片中一个像素点占的字节个数。
    我们假设拍出的照片的depth等于4,那么5312 * 2988大小的图片总共占用的内存为5312 * 2988 * 4 = 63489024(byte)。将其转为MB为63489024/1024/1024 = 60.55MB。

    android为bitmap提供的depth在Bitmap类中的Config枚举中有定义:ALPHA_8,RGB_565,ARGB_4444,ARGB_8888.如何理解这几个值呢?
    一个颜色值都是通过ARGB四个分量来描述(其中每个分量占一个字节),其中A:透明度(ALPHA) RGB分别表示红,绿,蓝三种颜色的值。RGB三种颜色值占用的比重不同就能描述出不同的颜色。

    • ALPHA_8:只存储颜色的ALPHA,不存储任何RGB分量,所以1byte就够了
    • RGB_565:只存储颜色的RGB,不存储ALPHA,总共占5+6+5/8=2个字节。其中5位存储R分量,接下来的6位存储G分量,最后的5位存储B分量
      剩下的几个大家应该自己能分析了,所以颜色深度(depth)最大的是ARGB_8888占了4个字节。

    综上,影响图片在内存中的大小主要取决于:

    1. 图片的大小
    2. 图片的颜色深度

    所以如何优化上面加载图片,旋转并保存图片想必大家就有思路了。

    1. 可以通过计算需要输出的图片的大小和原始图片的大小进行适当的压缩并计算sampleSize。
    2. 是酌情更改加载图片时指定使用颜色深度位RGB_565(主要针对没有透明度的JPG图片)
      演示代码如下:
      在AlbumAcitivity.java添加代码
    private int outWidth = 0;//输出bitmap的宽
    private int outHeight = 0;//输出bitmap的高
    //计算sampleSize
    private int caculateSampleSize(String imgFilePath,int rotate){
        outWidth = 0;
        outHeight = 0;
        int imgWidth = 0;//原始图片的宽
        int imgHeight = 0;//原始图片的高
        int sampleSize = 1;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(imgFilePath);
            BitmapFactory.decodeStream(inputStream,null,options);//由于options.inJustDecodeBounds位true,所以这里并没有在内存中解码图片,只是为了得到原始图片的大小
            imgWidth = options.outWidth;
            imgHeight = options.outHeight;
            //初始化
            outWidth = imgWidth;
            outHeight = imgHeight;
            //如果旋转的角度是90的奇数倍,则输出的宽和高和原始宽高调换
            if((rotate / 90) % 2 != 0){
                outWidth = imgHeight;
                outHeight = imgWidth;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
        //计算输出bitmap的sampleSize
        while (imgWidth / sampleSize > outWidth || imgHeight / sampleSize > outHeight) {
            sampleSize = sampleSize << 1;
        }
        return sampleSize;
    }
    private void doRotateImageAndSaveStrategy2(String filePath){
        int rotate = readPictureDegree(filePath);
        if(rotate == 0)
            return;
        //得到sampleSize
        int sampleSize = caculateSampleSize(filePath, rotate);
        if (outWidth == 0 || outHeight == 0)
            return;
    
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = sampleSize;
        //适当调整颜色深度
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inJustDecodeBounds = false;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            Bitmap srcBitmap = BitmapFactory.decodeStream(inputStream, null, options);//加载原图
            //test
            Bitmap.Config srcConfig = srcBitmap.getConfig();
            int srcMem = srcBitmap.getRowBytes() * srcBitmap.getHeight();//计算bitmap占用的内存大小
    
            Bitmap destBitmap = rotateImage(srcBitmap, rotate);
            int destMem = srcBitmap.getRowBytes() * srcBitmap.getHeight();
            srcBitmap.recycle();
    
            //保存bitmap到文件(覆盖原始图片)
            FileUtil.saveImageToSDCard(destBitmap, 100, filePath);
            destBitmap.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError error) {
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
    

    最后在doRotateImageAndSave方法中调用doRotateImageAndSaveStrategy2

    还是以拍照后图片大小为5312*2988为例,通过caculateSampleSize可以计算出outWidth和outHeight分别为2988和5312,sampleSize为2。核心代码是:

    if((rotate / 90) % 2 != 0){
          outWidth = imgHeight;
          outHeight = imgWidth;
    }
    while (imgWidth / sampleSize > outWidth || imgHeight / sampleSize > outHeight) {
           sampleSize = sampleSize << 1;
      }
    

    计算好了sampleSize为2后,再通过BitmapFactory.decodeStream并设置好对应的options,得到的bitmap的大小为:
    width=5312 / sampleSize 即:2656
    height=2988 / sampleSize 即:1494
    可以看出如果颜色深度保持和原图一样为4,经过处理后的bitmap占用的内存为2656*1494*4 = 15872256 转为MB为15.2MB, 是原始图片占用内存的1/4。如果我们再设置options的颜色深度为 options.inPreferredConfig = Bitmap.Config.RGB_565 如果原始图片颜色深度为Bitmap.Config.ARGB_8888,则最终bitmap占用的内存为:2656*1494*2 = 7936128 转为MB为7.56MB。

    OK,最后通过rotateImage方法对2656*1494的图片进行旋转(90度)操作后并保存到原始路径,所以最后保存的图片大小为1494*2656。以上解决方案虽然损失了些图片的清新度,但是却能极大的节省内存让OOM的概率将到最低。希望这篇文章能让大家明白计算sampleSize,如何计算bitmap占用的内存大小。

  • 相关阅读:
    我总结的面试题系列:kafka
    RabbitMQ大厂面试题
    [Algorithm] 并查集
    [LintCode] 编辑距离
    [LeetCode] Length of Longest Fibonacci Subsequence
    [LintCode] 交叉字符串
    [LeetCode] Permutation Sequence
    Permutation Sequence
    [LeetCode] Next Permutation
    [LeetCode] Longest Palindromic Substring
  • 原文地址:https://www.cnblogs.com/laoguigame/p/5526189.html
Copyright © 2011-2022 走看看