java - 如何在 android 中减小内存滑动加载的图像大小
问题描述
我正在尝试使用 glide 从 Internet 加载图像,但是对于我的应用程序来说尺寸太大(图像尺寸为 400X400,内存分配为 352KB,ImageView 的大小与图像尺寸相同),我已尝试在加载位图后对其进行解码,然后将其应用于 ImageView 但它不起作用,任何人都可以帮助我解决这个问题。
这是我的滑翔代码:
Glide.with(this)
.asBitmap()
.load(url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
int byteCount = resource.getAllocationByteCount();
int sizeInKB = (resource.getRowBytes() * resource.getHeight()) / 1024;
int sizeInMB = sizeInKB / 1024;
Glide.with(TestActivity.this)
.asBitmap()
.load(decodeSampledBitmapFromResource(resource, 400, 400))
.into(ss2);
sizeText.setText(sizeInKB + " KB");
}
});
这是解码位图的代码:
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) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Bitmap bitmap, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, blob);
byte[] bitmapData = blob.toByteArray();
BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bitmap.compress(Bitmap.CompressFormat.PNG, 0, blob);
byte[] bitmapData2 = blob.toByteArray();
return BitmapFactory.decodeByteArray(bitmapData2, 0, bitmapData2.length, options);
}
解决方案
图像的大小取决于很多因素,其中之一是它的尺寸和质量;默认情况下,Glide V4 中的质量格式为 ARGB_8888,因此如果您使用它,您可以将其更改为更小的 RGB_565。您可以在此处找到此信息和更多信息。
推荐阅读
- python - 我如何检查 Python 是不是我的 Flask 应用程序已经在后台运行
- sockets - 在 Django 频道中使用 RedisChannelLayer 时,长 URL(包括密钥)会导致 unicode idna 编解码器解码错误
- java - Spring Config Server - 属性覆盖
- azure - 在 Azure 持久函数中设置 MaxOrchestrationActions
- python - 为什么在 Python3 中发生列表索引超出范围
- excel - VBA Excel - 取几列的范围
- php - Laravel 6.x PostgreSQL 插入问题?SQLSTATE[22P02]:无效的文本表示:7 错误
- mysql - 需要从两个 MySQL 表创建一个动态矩阵
- python - 如何在两列之间创建转换矩阵?
- python - 我正在尝试使用 if 语句基于不同的数据框创建一个新的数据框