首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

Bit地图s 的重要有效方法 之一

2013-06-26 
Bitmaps 的重要有效方法 之一我们都知道BitmapFactory类提供几种解码方法 (decodeByteArray()、 decodeFile

Bitmaps 的重要有效方法 之一

我们都知道BitmapFactory类提供几种解码方法 (decodeByteArray()、 decodeFile()、 decodeResource()等) 从各种来源中创建一个Bitmap。选择最合适的解码方法基于您的图像数据源。这些方法尝试为构造位图分配内存,因此可以很容易有OutOfMemory异常的结果。

java.lang.OutofMemoryError: bitmap size exceeds VM budget.这种蛋疼的问题是因为CCD对每个android应用有内存限制16M,现在放宽了,但是如果把十几兆的图片直接显示出来那肯定是要挂滴。
怎么办咧?压缩小了的显示吧。

BitmapFactory.Options是关键

具体的做法是用两次解码!
第一次解码,其目的是测量尺寸,如果oom了也没关系
然后计算压缩比例
第二次解码,变小了
public static int calculateInSampleSize(
??????????? BitmapFactory.Options options, int reqWidth, int reqHeight) {
??? // Raw height and width of image
??? final int height = options.outHeight;
??? final int width = options.outWidth;
??? int inSampleSize = 1;

??? if (height > reqHeight || width > reqWidth) {

??????? // Calculate ratios of height and width to requested height and width
??????? final int heightRatio = Math.round((float) height / (float) reqHeight);
??????? final int widthRatio = Math.round((float) width / (float) reqWidth);

??????? // Choose the smallest ratio as inSampleSize value, this will guarantee
??????? // a final image with both dimensions larger than or equal to the
??????? // requested height and width.
??????? inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
??? }

??? return inSampleSize;
}

注:inSampleSize值是2 的幂。
inJustDecodeBounds设置为true

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
??????? int reqWidth, int reqHeight) {
??? Bitmap bm = null;
??? // First decode with inJustDecodeBounds=true to check dimensions
??? final BitmapFactory.Options options = new BitmapFactory.Options();
??? options.inJustDecodeBounds = true;
??? try {
??????? BitmapFactory.decodeResource(res, resId, options);
??? } catch (OutOfMemoryError e) {
??????? System.gc();
??? }

??? // Calculate inSampleSize
??? options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

??? // Decode bitmap with inSampleSize set
??? options.inJustDecodeBounds = false;
??? try {
??????? bm = BitmapFactory.decodeResource(res, resId, options);
??? } catch (OutOfMemoryError e) {
???????? System.gc();
??? }
??? return bm;
}

这种方法容易地将任意大小的位图加载到显示 100 x 100 像素的缩略图,如下面的代码示例所示:
mImageView.setImageBitmap(
??? decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));


?

热点排行