如果图片原本是RGB_565格式,确实比ARGB_8888格式少一半的内存 例如:
val options = BitmapFactory.Options()
//设置图片格式为RGB_565
options.inPreferredConfig = Bitmap.Config.RGB_565
//获取图片流
val ios = assets.open("anitque.png")
val optionsBitmap = BitmapFactory.decodeStream(ios, null, options)
相信大家都认为optionsBitmap色彩格式为RGB_565
val inputStream = assets.open("anitque.png")
val bitmap1 = BitmapFactory.decodeStream(inputStream)
Log.i("BITMAP", "默认格式 " + bitmap1.config.name)
val options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.RGB_565
val ios = assets.open("anitque.png")
val optionsBitmap = BitmapFactory.decodeStream(ios, null, options)
Log.i("BITMAP", "转换后格式 " + optionsBitmap.config.name)
结果:
默认格式 ARGB_8888
转换后格式 ARGB_8888
使用Glide
@GlideModule
class ConfGlideModule : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
super.applyOptions(context, builder)
//设置一个全局的配置
builder.setDefaultRequestOptions(RequestOptions().format(DecodeFormat.PREFER_RGB_565))
}
override fun isManifestParsingEnabled(): Boolean {
return false
}
}
Glide加载图片
GlideApp.with(default_iv).asBitmap().load(R.drawable.emerald)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?
) {
Log.i("BITMAP", "Glide格式 ${resource.config.name}")
}
})
结果:
Glide格式 ARGB_8888
通过查看源码得知原因:
/**
* If this is non-null, the decoder will try to decode into this
* internal configuration. If it is null, or the request cannot be met,
* the decoder will try to pick the best matching config based on the
* system's screen depth, and characteristics of the original image such
* as if it has per-pixel alpha (requiring a config that also does).
*
* Image are loaded with the {@link Bitmap.Config#ARGB_8888} config by
* default.
*/
public Bitmap.Config inPreferredConfig = Bitmap.Config.ARGB_8888;
翻译:如果非零,则解码器将尝试解码为该内部配置。 如果为null,或无法满足请求,则解码器将尝试根据系统的屏幕深度和原始图像的特征(例如,具有每像素的alpha值)选择最佳匹配的配置(要求配置也这样做)。
默认情况下,图像会使用{@link Bitmap.Config#ARGB_8888}配置加载。
由此可见,改配置并不是总能起到效果
解决方案:
public static Bitmap convert(Bitmap bitmap, Bitmap.Config config) {
Bitmap convertedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), config);
//创建一个画布
Canvas canvas = new Canvas(convertedBitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
canvas.drawBitmap(bitmap, 0, 0, paint);
bitmap.recycle();
return convertedBitmap;
}