Bitmap与BitmapFactory.Options

来源:互联网 发布:python足彩大数据分析 编辑:程序博客网 时间:2024/05/19 15:42

1.简介
当我们加载多张图片到内存的时候,因为图片过于大,会消耗大量的内存,这样很容易导致OOM,所以当我们加载图片的时候,我们不得不压缩其大小。因此我们需要用到BitmapFactory.Options这个类

2.使用
第一步都是先获取Options对象:
Options tOptions = new BitmapFactory.Options();

第二步分为两种方案:

方案一:直接通过Options设置一个大小压缩
设置Options两个属性:
1.tOptions.inJustDecodeBounds = false; 这个属性若设置为True则不加载Bitamp对象,而是返回一个只有宽高Bitmap,你可以获取,原图的宽高,这里我们采用直接压缩法,所以不设置。

附Api解释:
If set to true, the decoder will return null (no bitmap), but the out… fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

2.tOpitons.inSampleSize = 10; 这个属性是用来直接设置其压缩比例。若设置为10,则原宽高缩小10倍,像素缩小100倍。
附Api解释:

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder will try to fulfill this request, but the resulting bitmap may have different dimensions that precisely what has been requested. Also, powers of 2 are often faster/easier for the decoder to honor.

具体实现

方案二:通过返回其空位图的宽高,计算压缩比例获取不变形的位图:
1.tOptions.inJustDecodeBounds = true;这里设置为true,因为我们仅仅需要获取位图的宽高就可以计算压缩的宽高

2.获取位图:
Bitmap tTempBitmap = BitmapFactory.decodeFile(mPath,tOptions);

3.开始通过宽高获取压缩比例:(此处为获取宽为200的不变形位图)
Int height = tOptions.outHeight *200 / tOptions.outWidth;
tOptions.outWidth = 200;
tOptions.outHeight = height;
tOptions. inJustDecodeBounds = fasle;
Bitmap tTargetBitmap = BitmapFactory.decodeFile(mPath,tOptions);

最后获取完毕;

附Api:
outWidth:
The resulting width of the bitmap, set independent of the state of inJustDecodeBounds. However, if there is an error trying to decode, outWidth will be set to -1.

outHeight:
The resulting height of the bitmap, set independent of the state of inJustDecodeBounds. However, if there is an error trying to decode, outHeight will be set to -1.

0 0
原创粉丝点击