首页 > 解决方案 > Using Glide, is it possible to get output image resolution, before the actual decoding and saving into a bitmap?

问题描述

Background

I'm trying to have a horizontally scrolling effect on any given image file in a live wallpaper app.

For this, I should work according to these rules, I think:

The problem

I'm finding difficulties finding the correct functions and parameters to make it generate the proper width&height of the output bitmap.

What I've tried

I've tried messing around with various transformations (example: centerCropTransform,fitCenterTransform) , but none of those reached what I wanted, so I think that none can work unless I do some special math on my side before deciding what to do with Glide.

Currently what I do is something like that:

val result = Glide.with(context).asBitmap()
                           .load(imageFile)
                           .apply(RequestOptions.noTransformation()
                           .skipMemoryCache(true)
                           .diskCacheStrategy(DiskCacheStrategy.NONE))
                           .submit(reqWidth, reqHeight).get()

This works, as it produces (at least according to my tests) a bitmap that is at least of the size I request it to be. However, it means I have extra pixels that aren't really needed for the height. It also doesn't protect me from generating a too large bitmap.

But I think maybe it would be easier to ask Glide to use various techniques for the above purpose, and then decide on the possible output resolutions, which is the best to use.

The questions

  1. Is it possible to get the output resolution before the actual decoding&storing into a bitmap, and only later decide which technique should be used?

  2. Is there maybe a better option I should consider ? Maybe do the calculation on my side, and then decide what to do with Glide? If so, how?

标签: androidbitmapscalecropandroid-glide

解决方案


  • 我应该缩放/裁剪,以便高度具有特定值。
  • 宽度至少应为特定值
  • 无论如何保持纵横比。

你不能真的把所有这些都说成是真的,因为如果你有一个保证的最小高度和一个保证的最小宽度,那么你可能不得不扭曲纵横比,这违反了第三个条件。

我建议改为使用以下三个条件:

  1. 将输出的最大高度设置为设备屏幕的高度(纵向)
  2. 设置输出位图的最大分配内存
  3. 无论如何保持原始纵横比

Glide 可以为您执行 1 和 3,但 2 您可能需要先解码位图而不分配内存(查看BitmapFactory.Options.inJustDecodeBounds)以获取源纵横比,然后使用数学计算出要设置的高度和宽度,这样您就不会过度您的每位图内存上限。

最后一件事,根据您的用例(如果您需要在短时间内渲染多个位图),您可能需要考虑裁剪为标准输出纵横比,以便您可以利用 Glide 的位图回收功能,这有助于避免 OOM 崩溃。


推荐阅读