android图片压缩

首先该文章是总结, 不是原创, 是通过看网上其他大神的文章和自己的一些实践总结出来的.

一 图片的存在形式:

  • 1.文件形式(即以二进制形式存在于硬盘上)
  • 2.流的形式(即以二进制形式存在于内存中)
  • 3.Bitmap形式
  • 这三种形式的区别: 文件形式和流的形式对图片体积大小并没有影响,也就是说,如果你手机SD卡上的如果是100K,那么通过流的形式读到内存中,也一定是占100K的内存,注意是流的形式,不是Bitmap的形式,当图片以Bitmap的形式存在时,其占用的内存会瞬间变大, 我试过500K文件形式的图片加载到内存,以Bitmap形式存在时,占用内存将近10M,当然这个增大的倍数并不是固定的

已经验证

从图中可以看出

  • 1、拍摄完的照片文件大小和读取到内存中的文件流大小是一样的,说明文件形式和流的形式对图片体积大小并没有影响
  • 2、当图片以Bitmap形式存在时,占用的内存就大的多了,为什么 呢,首先我们需要知道Bitmap大小计算的方式:bitmap大小=图片长度(px)图片宽度(px)单位像素占用的字节数
  • 单位像素所占字节数又是什么鬼,说白了就是图片的色彩模式。
    在BitmapFactory.Options.inPreferredConfig这里可以找到,一共有4种, ARGB代表:A 透明度 , R 红色, G 绿色, B 蓝色

二 图片的压缩形式

  • 问:我们从本地对图片操作的目的是?
  • 答:上传(比如设置头像,发表图片)。
上传的基本步骤:
这里写图片描述
  • 问:我们为什么要压缩图片呢

  • 答:目的无非就2个,一,避免占用内存过多。二,可能要上传图片,如果图片太大,浪费流量。(有时候需要上传原图除外)

  • 1、避免内存过多的压缩方法:归根结底,图片是要显示在界面组件上的,所以还是要用到bitmap,从上面可得出Bitmap的在内存中的大小只和图片尺寸和色彩模式有关,那么要想改变Bitmap在内存中的大小,要么改变尺寸,要么改变色彩模式。

  • 2、避免上传浪费流量的压缩方法:改变图片尺寸,改变色彩模式,改变图片质量都行。正常情况下,先改变图片尺寸和色彩模式,再改变图片质量。

改变图片质量的压缩方法

/**
 * 
 * 根据bitmap压缩图片质量
 * @param bitmap 未压缩的bitmap
 * @return 压缩后的bitmap
 */
public static Bitmap cQuality(Bitmap bitmap){
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    int beginRate = 100;
    //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差  ,第三个参数:保存压缩后的数据的流
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
    while(bOut.size()/1024/1024>100){  //如果压缩后大于100Kb,则提高压缩率,重新压缩
        beginRate -=10;
        bOut.reset();
        bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
    }
    ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
    Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
    if(newBitmap!=null){
        return newBitmap;
    }else{
        return bitmap;
    }
}

改变图片大小的压缩算法:

public static boolean getCacheImage(String filePath,String cachePath){
    OutputStream out = null;
    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inJustDecodeBounds = true;  //设置为true,只读尺寸信息,不加载像素信息到内存
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, option);  //此时bitmap为空
    option.inJustDecodeBounds = false;
    int bWidth = option.outWidth;
    int bHeight= option.outHeight;
    int toWidth = 400;
    int toHeight = 800;
    int be = 1;  //be = 1代表不缩放
    if(bWidth/toWidth>bHeight/toHeight&&bWidth>toWidth){
        be = (int)bWidth/toWidth;
    }else if(bWidth/toWidth<bheight bheight="">toHeight){
        be = (int)bHeight/toHeight;
    }
    option.inSampleSize = be; //设置缩放比例
    bitmap  = BitmapFactory.decodeFile(filePath, option);
    try {
        out = new FileOutputStream(new File(cachePath));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bitmap.compress(CompressFormat.JPEG, 100, out);
}

正常情况下我们应该把两者相结合的,所以有了下面的算法(在项目中直接用,清晰度在手机上没问题)

public static File scal(Uri fileUri){
    String path = fileUri.getPath();
    File outputFile = new File(path);
    long fileSize = outputFile.length();
    final long fileMaxSize = 200 * 1024;
     if (fileSize >= fileMaxSize) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;

            double scale = Math.sqrt((float) fileSize / fileMaxSize);
            options.outHeight = (int) (height / scale);
            options.outWidth = (int) (width / scale);
            options.inSampleSize = (int) (scale + 0.5);
            options.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            outputFile = new File(PhotoUtil.createImageFile().getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d(, sss ok  + outputFile.length());
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }else{
                File tempFile = outputFile;
                outputFile = new File(PhotoUtil.createImageFile().getPath());
                PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
            }

        }
     return outputFile;

}

上面用到两个方法

public static Uri createImageFile(){
    // Create an image file name
    String timeStamp = new SimpleDateFormat(yyyyMMdd_HHmmss).format(new Date());
    String imageFileName = JPEG_ + timeStamp + _;
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = null;
    try {
        image = File.createTempFile**(
            imageFileName,  /* prefix */
            .jpg,         /* suffix */
            storageDir      /* directory */
        );
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // Save a file: path for use with ACTION_VIEW intents
    return Uri.fromFile(image);
}

public static void copyFileUsingFileChannels(File source, File dest){
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } finally {
        try {
            inputChannel.close();
            outputChannel.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值