Android 图片压缩即生成缩略图方法-BitmapFacotry.Options。

Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息,进行图像剪切、旋转、缩放等操作,并可以指定格式保存图像文件。

一、Bitmap的生成

1.1 BitmapFactory decode出Bitmap

利用BitmapFactory可以从一个指定文件中,利用decodeFile()解出Bitmap;

也可以定义的图片资源中,利用decodeResource()解出Bitmap。

 1.2 decode时的选项

在使用方法decodeFile()/decodeResource()时,都可以指定一个BitmapFacotry.Options

利用Options的下列属性,可以指定decode的选项:

  • inPreferredConfig 指定decode到内存中,手机中所采用的编码,可选值定义在Bitmap.Config中。缺省值是ARGB_8888。
  • inJustDecodeBounds 如果设置为true,并不会把图像的数据完全解码(把它设为true,那么BitmapFactory.decodeFile(String path, Options opt)并不会真的返回一个Bitmap给你,它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了。 
  • inSampleSize 设置decode时的缩放比例。

  利用Options的这些值就可以高效的得到一幅缩略图。

过程:先设置inJustDecodeBounds= true,利用图像的实际宽度(或者高度,或综合)以及你想设置的宽度,得到inSampleSize值(值越大,缩略图越小),再设置inJustDecodeBounds= false,最后调用decodeFile()得到完整的图像数据。

代码示例:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp =BitmapFactory.decodeResource(Resources res, R.id.Test, options);/* 这里返回的bitmap是null */

//reqWidth, reqHeight是你想设置的图片的宽度和高度
options.inSampleSize = A(options, reqWidth, reqHeight);

// 使用获取到的inSampleSize值再次解析图片

options.inJustDecodeBounds = false;

Bitmap bmp =BitmapFactory.decodeResource(Resources res, R.id.Test, options);/* 这里返回的bitmap是有值的 */

A方法:public static int A(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// 源图片的高度和宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;//设置默认值
if (height > reqHeight || width > reqWidth) {
// 计算出图片的实际宽高和你想设置的宽高的比率
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值