android decodebytearray 内存溢出,彻底解决Android因加载多个大图引起的OutOfMemoryError,内存溢出的问题...

这段代码展示了如何使用BitmapFactory在Java中实现图片的压缩和尺寸调整。通过计算采样大小并创建缩放比例,确保图片加载时不超过指定的最大像素数,同时保持较好的质量。该方法包括内存管理和错误处理,旨在优化内存使用和提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static byte[] decodeBitmap(String path) {

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

opts.inJustDecodeBounds = true;// 设置成了true,不占用内存,只获取bitmap宽高

BitmapFactory.decodeFile(path, opts);

opts.inSampleSize = computeSampleSize(opts, -1, 1024 * 800);

opts.inJustDecodeBounds = false;// 这里一定要将其设置回false,因为之前我们将其设置成了true

opts.inPurgeable = true;

opts.inInputShareable = true;

opts.inDither = false;

opts.inPurgeable = true;

opts.inTempStorage = new byte[16 * 1024];

FileInputStream is = null;

Bitmap bmp = null;

ByteArrayOutputStream baos = null;

try {

is = new FileInputStream(path);

bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);

double scale = getScaling(opts.outWidth * opts.outHeight,

1024 * 600);

Bitmap bmp2 = Bitmap.createScaledBitmap(bmp,

(int) (opts.outWidth * scale),

(int) (opts.outHeight * scale), true);

bmp.recycle();

baos = new ByteArrayOutputStream();

bmp2.compress(Bitmap.CompressFormat.JPEG, 100, baos);

bmp2.recycle();

return baos.toByteArray();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

is.close();

baos.close();

} catch (IOException e) {

e.printStackTrace();

}

System.gc();

}

return baos.toByteArray();

}

private static double getScaling(int src, int des) {

/**

* 48 目标尺寸÷原尺寸 sqrt开方,得出宽高百分比 49

*/

double scale = Math.sqrt((double) des / (double) src);

return scale;

}

public static int computeSampleSize(BitmapFactory.Options options,

int minSideLength, int maxNumOfPixels) {

int initialSize = computeInitialSampleSize(options, minSideLength,

maxNumOfPixels);

int roundedSize;

if (initialSize <= 8) {

roundedSize = 1;

while (roundedSize 

roundedSize <<= 1;

}

} else {

roundedSize = (initialSize + 7) / 8 * 8;

}

return roundedSize;

}

private static int computeInitialSampleSize(BitmapFactory.Options options,

int minSideLength, int maxNumOfPixels) {

double w = options.outWidth;

double h = options.outHeight;

int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math

.sqrt(w * h / maxNumOfPixels));

int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(

Math.floor(w / minSideLength), Math.floor(h / minSideLength));

if (upperBound 

return lowerBound;

}

if ((maxNumOfPixels == -1) && (minSideLength == -1)) {

return 1;

} else if (minSideLength == -1) {

return lowerBound;

} else {

return upperBound;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值