Android开发之图片详解(5)

来源:互联网 发布:无线网络转换有线网络 编辑:程序博客网 时间:2024/05/22 11:38

这是关于图片的最后一篇。
主要说下bitmap怎么压缩,几种压缩方法,及其应用场景。
这里我举了一个拍照显示的场景,这个场景其实用的也是比较多的。
先上示例代码:

package com.example.imagetext;import java.io.File;import java.io.IOException;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.graphics.BitmapFactory.Options;import android.media.ExifInterface;import android.net.Uri;import android.os.Build;import android.os.Bundle;import android.provider.MediaStore;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity {    private ImageView iv,iv2,iv1;    private Button bt;    private Uri mImageUri;    private Bitmap bitmap1,bitmap2,bitmap;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        init();    }    private void init(){        mImageUri = getTempFileUri("temp/text.jpg",this);        iv = (ImageView) findViewById(R.id.iv);        iv2 = (ImageView) findViewById(R.id.iv2);        iv1 = (ImageView) findViewById(R.id.iv1);        bt = (Button) findViewById(R.id.bt);        bt.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                takePhoto();            }        });    }    @SuppressLint("NewApi")    public long getBitmapsize(Bitmap bitmap) {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {            return bitmap.getByteCount();        }        // Pre HC-MR1        return bitmap.getRowBytes() * bitmap.getHeight();    }       //bitmap按2的幂次方压缩    private Bitmap handleBitmap(Uri uri,int maxWith,int maxHeight){        Options options = new Options();        options.inJustDecodeBounds=true;        Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath(), options);        int realWith = options.outWidth;        int realHeight = options.outHeight;        int bw = realWith/maxWith;        int bh =realHeight/maxHeight;        if(Math.max(bw, bh)!=0){            options.inSampleSize = Math.max(bw, bh);        }        options.inJustDecodeBounds = false;        //options.inPreferredConfig = Bitmap.Config.RGB_565;        bitmap = BitmapFactory.decodeFile(uri.getPath(), options);        //如果照片被旋转了,则旋转回来        ExifInterface exifInterface = null;        try {            exifInterface = new ExifInterface(uri.getPath());        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        int tag = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);        int degree = 0;        if (tag == ExifInterface.ORIENTATION_ROTATE_90) {            degree = 90;        } else if (tag == ExifInterface.ORIENTATION_ROTATE_180) {            degree = 180;        } else if (tag == ExifInterface.ORIENTATION_ROTATE_270) {            degree = 270;        }        if (degree != 0 && bitmap != null) {            Matrix m = new Matrix();            m.setRotate(degree, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);        }        return  bitmap;    }    //将bitmap精确缩放    private Bitmap handleBitmapDetail(Bitmap bitmap,float detailWith,float detailHeight){        float bw= detailWith/bitmap.getWidth();        float bh = detailHeight/bitmap.getHeight();        Matrix matrix = new Matrix();        matrix.setScale(bw, bh);        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);        return bitmap;    }    //将照片原图加载到bitmap中    private Bitmap getRealBitmap(Uri uri){        Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());        return bitmap;    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        // TODO Auto-generated method stub        super.onActivityResult(requestCode, resultCode, data);        if(resultCode!=RESULT_OK){            return;        }        if(requestCode==1){            Bitmap bitmap = handleBitmap(mImageUri,100,100);            iv.setImageBitmap(bitmap);            Bitmap bitmap1 = handleBitmapDetail(bitmap,150,150);            iv1.setImageBitmap(bitmap1);            Bitmap bitmap2 = getRealBitmap(mImageUri);            iv2.setImageBitmap(bitmap2);            Log.e("tttext","bitmap:"+bitmap.getWidth()+"px"+bitmap.getHeight()+"px"+getBitmapsize(bitmap)/1024+"K");            Log.e("tttext","bitmap:"+bitmap1.getWidth()+"px"+bitmap1.getHeight()+"px"+getBitmapsize(bitmap1)/1024+"K");            Log.e("tttext","bitmap:"+bitmap2.getWidth()+"px"+bitmap2.getHeight()+"px"+getBitmapsize(bitmap2)/1024/1024+"M");        }    }    @Override    protected void onDestroy() {        // TODO Auto-generated method stub        super.onDestroy();        if(!bitmap.isRecycled()){            bitmap.recycle();        }        if(!bitmap1.isRecycled()){            bitmap1.recycle();        }        if(!bitmap2.isRecycled()){            bitmap2.recycle();        }    }    //拍照    private void takePhoto(){        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);        startActivityForResult(intent, 1);    }    //创建一个临时文件    public  Uri getTempFileUri(String fileName,Context context) {        return Uri.fromFile(getTempFile(fileName,context));    }    public  File getTempFile(String fileName,Context context) {        File rootCache = context.getExternalCacheDir();        if (rootCache == null) {            rootCache = context.getCacheDir();        }        File cacheDir = new File(rootCache, fileName);        cacheDir.getParentFile().mkdirs();        try {            cacheDir.createNewFile();        } catch (IOException e) {        }        return cacheDir;    }}

这是效果图:
这里写图片描述

这是打印结果:
这里写图片描述

1.首先,大家可以看看 这个方法,private Bitmap handleBitmap(Uri uri,int maxWith,int maxHeight)

这个方法的意思是先将options.inJustDecodeBound设置为true;这个时候只是获取到图片的宽高信息,并没有将bitmap加载到内存中,这个时候获取到的bitmap是null(其实大家也可以看到,相片原图是2448px*3264px,占用内存30M,如果在有的内存小的手机上很可能就直接OOM了),然后我们可以根据我们想要压缩的目标宽高计算出缩放的倍数,也就是这个参数:options.inSampleSize,这里要注意的是,这个参数只能是2的幂次方,就算你设置成7,他也会寻找最接近的8去压缩。
所以这种压缩方式 是可以保持原图的宽高比例的。

2.然后是这个方法,private Bitmap handleBitmapDetail(Bitmap bitmap,float detailWith,float detailHeight)

这个方法的意思是将bitmap精确压缩到指定宽高,但是原图的宽高比例就可能发生变化,大家从截图里面也可以清楚的看到。

3.那么这两个方法有什么区别呢,第一个方法效率是最高的,而且不需要先将bitmap加载到内存中,也是防止内存溢出的最有效的方法。大家可以在打印的截图里面看到,压缩过后的bitmap占用的内存仅有几十K。缺点就是无法精确压缩到指定像素。而第二个方法虽然可以压缩至指定像素,但是可能会改变原图的宽高比例,而且,效率是相当低的,而且还必须要先获取到bitmap,所以我们一般是将两方法结合起来使用的。

4.关于这个参数options.inPreferredConfig = Bitmap.Config.RGB_565;
其实这都是色彩的存储方法:我们知道ARGB指的是一种色彩模式,里面A代表Alpha,R表示red,G表示green,B表示blue,其实所有的可见色都是右红绿蓝组成的,所以红绿蓝又称为三原色,每个原色都存储着所表示颜色的信息值

说白了就ALPHA_8就是Alpha由8位组成
ARGB_4444就是由4个4位组成即16位,
ARGB_8888就是由4个8位组成即32位,
RGB_565就是R为5位,G为6位,B为5位共16位

Android默认的是ARGB_8888,如果非要牺牲图片质量去减小内存的话,我们可以自己设置成RGB_565,内存将再缩小一倍,不过我不建议就是了,因为我们完全可以通过PX去缩小内存。

5.关于bitmap的回收,在这里,我在onDestroy方法里对bitmap进行了回收,这是可以并且也是有必要的,因为这个场景是从相册里面读取的图片,是不会被复用的,也就是说每次读取都是重新创建对象的过程,如果这里场景是iv.setimageDrawable,是从资源文件夹里读取的图片,那么根据我上篇文章中讲到的资源文件夹的复用机制吗,就不要去手动回收它了,否则很可能在之后的操作中出现使用已回收图片的异常。

6.除了这个场景以外,从网络上加载或者上传图片也可以这样处理。大家还可以结合软引用/弱引用一起处理,设置一个缓存机制。这里我就不再详细介绍了。大家有兴趣的可以看看ImageLoader的源码,其实人家已经很好的实现了这一点。

好的,关于Android图片处理就说到这里。

1 0