mPreview = BitmapFactory.decodeStream(HttpsImage.getStream(mPreviewUrl));

崩溃日志

java.lang.OutOfMemoryError: Failed to allocate a 8294412 byte allocation with 2618916 free bytes and 2MB until OOM

at dalvik.system.VMRuntime.newNonMovableArray(Native Method)

at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:853)

at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:829)

at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:867)

at com.sengled.Snap.ui.holder.HolderMySnap$1.doInAsyncThread(HolderMySnap.java:357)

at com.sengled.common.task.BaseTask.run(BaseTask.java:27)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

at java.lang.Thread.run(Thread.java:818)

在android中的大图片一般都要经过压缩才能显示,不然容易发生oom 一般我们压缩的时候都只关注其尺寸方面的大小,其实除了尺寸之外,影响一个图片占用空间的还有其色彩细节。

1 大小

BitmapFactory.Options options = new BitmapFactory.Options();

options.inSampleSize = 2; //图片宽高都为原来的二分之一,即图片为原来的四分一

google zxing

BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true; // 先获取原大小

Bitmap scanBitmap = BitmapFactory.decodeFile(path, options);

options.inJustDecodeBounds = false; // 获取新的大小

int sampleSize = (int) (options.outHeight / (float) 200);

if (sampleSize <= 0){

sampleSize = 1;

} else if ( sampleSize > 6 ){

sampleSize = 6;

}

options.inSampleSize = sampleSize;

scanBitmap = BitmapFactory.decodeFile(path, options);

注意

scanBitmap.recycle();

scanBitmap = null ;

2 色彩 Android.graphics.Bitmap类里有一个内部类Bitmap.Config类,在Bitmap类里createBitmap(intwidth, int height, Bitmap.Config config)方法里会用到,打开个这个类一看

public enum Config {

public static final Bitmap.Config ALPHA_8

public static final Bitmap.Config ARGB_4444

public static final Bitmap.Config ARGB_8888

public static final 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位

由此可见:

ALPHA_8 代表8位Alpha位图

ARGB_4444 代表16位ARGB位图

ARGB_8888 代表32位ARGB位图

RGB_565 代表8位RGB位图

位图位数越高代表其可以存储的颜色信息越多,当然图像也就越逼真。

用法:

在压缩之前将option的值设置一下:

options.inPreferredConfig = Bitmap.Config.RGB_565;

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐