zoukankan      html  css  js  c++  java
  • Android 循环压缩图片内存大小控制指定范围内

    一:实现过程

    使用以下代码压缩循环压缩

      /**
         * 质量压缩方法
         *
         * @param image
         * @return
         */
        public static File compressImage(Bitmap image) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
            int options = 90;
            while (baos.size() > 153600) { // 循环判断如果压缩后图片是否大于150kb,大于继续压缩
                baos.reset(); // 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
                options = options - 10;// 每次都减少10
            }
            UtilsLog.e(options + " " + baos.size());
            String sdCardDir = Environment.getExternalStorageDirectory() + "/qcjrHuaXia/";
            File file = null;
            try {
                File dirFile = new File(sdCardDir);
                if (!dirFile.exists()) {              //如果不存在,那就建立这个文件夹
                    dirFile.mkdirs();
                }
                String fileName = String.valueOf(System.currentTimeMillis());
                file = new File(sdCardDir, fileName + ".jpg");
                FileOutputStream fos = new FileOutputStream(file);
                baos.writeTo(fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            UtilsLog.e(" options123-->" + file.length());
            return file;
        }

    代码虽然只控制了不能大于150Kb,但是出来的图片大小几乎都符合我需求的100kb~150Kb范围内,因为他每次都压缩质量不是很大。

    二:遇到的问题

    虽然上面内实现图片压缩,但是超过1MB的图片,压缩会很慢。然而现在手机拍出的图片几乎都是6MB左右的样子。

    所以为了优化节省压缩时间,我采用了,

    先通过在github上找的图片压缩工具CompressHelper,(附上地址 https://github.com/nanchen2251/CompressHelper)

    先把超过1MB的图片压缩一下,更改了默认的压缩设置防止其压缩率太大.

     public File compressToFile(File file, int num) {
            return BitmapUtil.compressImage(context, Uri.fromFile(file), 1080, 1920,
                    compressFormat, bitmapConfig, num, destinationDirectoryPath,
                    fileNamePrefix, fileName);
        }

    之后在把这个压缩后的图片,在进行循环压缩,就很快了。

    需求达成。

  • 相关阅读:
    8.使用axios实现登录功能
    7.django配置跨域并开发测试接口
    9.Vue组件
    2.初始化项目结构
    1.Django基础
    团队冲刺——第七天
    团队冲刺——第六天
    十天冲刺——第五天
    十天冲刺——第四天
    十天冲刺——第三天
  • 原文地址:https://www.cnblogs.com/niupi/p/11287178.html
Copyright © 2011-2022 走看看