这篇文章主要介绍了 Android 实现简单图片压缩的方法, 详细分析了 Android 针对图片的读取、缩放及保存等操作技巧, 需要的朋友可以参考下
Android 是一种基于 Linux 的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由 Google 公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用 "安卓" 或 "安致"。
本文实例讲述了 Android 实现简单图片压缩的方法。分享给大家供大家参考,具体如下:
在开发图片浏览器等软件是,很多时候要显示图片的缩略图,而一般情况下,我们要将图片按照固定大小取缩略图,一般取缩略图的方法是使用 BitmapFactory 的 decodeFile 方法,然后通过传递进去 BitmapFactory.Option 类型的参数进行取缩略图,在 Option 中,属性值 inSampleSize 表示缩略图大小为原始图片大小的几分之一,即如果这个值为 2,则取出的缩略图的宽和高都是原始图片的 1/2,图片大小就为原始大小的 1/4。
然而,如果我们想取固定大小的缩略图就比较困难了,比如,我们想将不同大小的图片去出来的缩略图高度都为 200px,而且要保证图片不失真,那怎么办? 我们总不能将原始图片加载到内存中再进行缩放处理吧,要知道在移动开发中,内存是相当宝贵的,而且一张 100K 的图片,加载完所占用的内存何止 100K
我们发现,Options 中有个属性 inJustDecodeBounds,SDK 中的英文引用如下:
If set totrue, the decoder will return null (no bitmap), but the out... fields will stillbe set, allowing the caller to query the bitmap without having to allocate thememory for its pixels.
意思就是说如果该值设为 true 那么将不返回实际的 bitmap 不给其分配内存空间而里面只包括一些解码边界信息即图片大小信息,那么相应的方法也就出来了,通过设置 inJustDecodeBounds 为 true,获取到 outHeight(图片原始高度) 和 outWidth(图片的原始宽度),然后计算一个 inSampleSize(缩放值),然后就可以取图片了,这里要注意的是,inSampleSize 可能小于 0,必须做判断。
具体代码如下:
- FrameLayout fr=(FrameLayout)findViewById(R.id.FrameLayout01);
- BitmapFactory.Options options =new BitmapFactory.Options();
- options.inJustDecodeBounds =true;
- // 获取这个图片的宽和高
- Bitmap bitmap =BitmapFactory.decodeFile("/sdcard/test.jpg", options); //此时返回bm为空
- options.inJustDecodeBounds =false;
- //计算缩放比
- int be = (int)(options.outHeight/ (float)200);
- if (be <= 0)
- be = 1;
- options.inSampleSize = be;
- //重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
- bitmap=BitmapFactory.decodeFile("/sdcard/test.jpg",options);
- int w = bitmap.getWidth();
- int h = bitmap.getHeight();
- System.out.println(w+" "+h);
- ImageView iv=new ImageView(this);
- iv.setImageBitmap(bitmap);
这样我们就可以读取较大的图片而不会内存溢出了。如果你想把压缩后的图片保存在 Sdcard 上的话就很简单了:
- File file=new File("/sdcard/feng.png");
- try {
- FileOutputStream out=newFileOutputStream(file);
- if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){
- out.flush();
- out.close();
- }
- } catch (FileNotFoundException e){
- // TODO Auto-generated catchblock
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catchblock
- e.printStackTrace();
- }
希望本文所述对大家 Android 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0324/238068.html