Android图像常用压缩技术 详细讲解啊

来源:互联网 发布:知乎书店推荐 编辑:程序博客网 时间:2024/05/29 17:55

近期在做图片上传的功能,从相机拍摄或从相册选区。就研究了这方面的东西

一.图片的基本知识

1.文件形式(即以二进制形式存在于硬盘上)
获取大小(Byte):File.length()
2.流的形式(即以二进制形式存在于内存中)
获取大小(Byte):new FileInputStream(File).available()
3.Bitmap形式
获取大小(Byte):Bitmap.getByteCount()

下面以我拍摄的图片为例,看下三者的大小区别(所用软件为自己临时开发的小工具);

\

小笨鸟出口平台,3秒一个订单
【点击进入】
3000元,一对一商务服务,一键布局全球卖场 60亿美元销售额,国货出口 so easy!

\

北京动力节点java培训
【点击进入】
动力节点-口口相传的java黄埔军校, 专注java教学7年,老学员力荐品牌.

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

\

德恒通办公用品,满百免运费!
【点击进入】
一站式高效优质服务,品种全,价格低, 德恒通办公,让您一身轻松(010)82117048

 

 

上面的bitmap在内存中的大小就可以计算了(默认色彩模式为ARGB_8888),

2368*4224*4/1024/1024=38.15625

看到bitmap占用这么大,所以用完调用Bitmap.recycle()是个好习惯(推荐),不调用也没关系,因为GC进程会自动回收。

二 图片的压缩形式

问:我们从本地对图片操作的目的。是

答:上传(比如设置头像,发表图片)。

上传的基本步骤

\
德恒通办公用品,满百免运费!
【点击进入】
一站式高效优质服务,品种全,价格低, 德恒通办公,让您一身轻松(010)82117048


那么问题来了

 

问:我们为什么要压缩图片呢

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

1、避免内存过多的压缩方法:

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

2、避免上传浪费流量的压缩方法:

改变图片尺寸,改变色彩模式,改变图片质量都行。正常情况下,先改变图片尺寸和色彩模式,再改变图片质量。

 

改变图片质量的压缩方法:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
     *
     * 根据bitmap压缩图片质量
     * @param bitmap 未压缩的bitmap
     * @return 压缩后的bitmap
     */
    publicstatic Bitmap cQuality(Bitmap bitmap){
        ByteArrayOutputStream bOut = newByteArrayOutputStream();
        intbeginRate = 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 = newByteArrayInputStream(bOut.toByteArray());
        Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
        if(newBitmap!=null){
            returnnewBitmap;
        }else{
            returnbitmap;
        }
    }


 

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

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
publicstatic boolean getCacheImage(String filePath,String cachePath){
        OutputStream out = null;
        BitmapFactory.Options option = newBitmapFactory.Options();
        option.inJustDecodeBounds = true//设置为true,只读尺寸信息,不加载像素信息到内存
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, option);  //此时bitmap为空
        option.inJustDecodeBounds = false;
        intbWidth = option.outWidth;
        intbHeight= option.outHeight;
        inttoWidth = 400;
        inttoHeight = 800;
        intbe = 1//be = 1代表不缩放
        if(bWidth/toWidth>bHeight/toHeight&&bWidth>toWidth){
            be = (int)bWidth/toWidth;
        }elseif(bWidth/toWidth<bheight bheight="">toHeight){
            be = (int)bHeight/toHeight;
        }
        option.inSampleSize = be; //设置缩放比例
        bitmap  = BitmapFactory.decodeFile(filePath, option);
        try{
            out = newFileOutputStream(newFile(cachePath));
        }catch(IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        returnbitmap.compress(CompressFormat.JPEG, 100, out);
    }</bheight>


 

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

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
publicstatic File scal(Uri fileUri){
        String path = fileUri.getPath();
        File outputFile = newFile(path);
        longfileSize = outputFile.length();
        finallong fileMaxSize = 200* 1024;
         if(fileSize >= fileMaxSize) {
                BitmapFactory.Options options = newBitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(path, options);
                intheight = options.outHeight;
                intwidth = options.outWidth;
 
                doublescale = 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 = newFile(PhotoUtil.createImageFile().getPath());
                FileOutputStream fos = null;
                try{
                    fos = newFileOutputStream(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 = newFile(PhotoUtil.createImageFile().getPath());
                    PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
                }
                 
            }
         returnoutputFile;
         
    }


 

上面算法中用到的两个方法:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
publicstatic Uri createImageFile(){
        // Create an image file name
        String timeStamp = newSimpleDateFormat(yyyyMMdd_HHmmss).format(newDate());
        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
        returnUri.fromFile(image);
    }
    publicstatic void copyFileUsingFileChannels(File source, File dest){
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try{
            try{
                inputChannel = newFileInputStream(source).getChannel();
                outputChannel = newFileOutputStream(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();
            }
        }
    }


 

最好的算法参考了coding客户端上传照片的操作算法,并简化了操作,已经实际测试,没有问题。

最后会上传临时根据这个算法做的从相册和相机选取照片的小demo,功能完整。

0 0
原创粉丝点击