首页 > 解决方案 > 我如何从云存储下载像 Whatsapp 这样的图像

问题描述

我想从云存储下载像 WhatsApp 这样的图像,比如当用户在 Recyclerview 中时,他看到的图像质量很低,但是当他点击图像时,它会以全分辨率下载,目前我正在做的是使用 glide 库下载图像。

目前我正在做的是,但它以全分辨率下载recyclerview中的图像。

 if (user.getImageURL().equals("default")) {
                profile_image.setImageResource(R.drawable.user2);
            } else {
                //and this
                Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
            }

标签: androidandroid-glide

解决方案


使用 Glide 的 CustomTarget 传递图像视图的尺寸,以便 Glide 可以将图像缩小到指定的大小。

Glide.with(this)
    .load(IMAGE_URL)
    .into(object : CustomTarget<Drawable>(targetImageWidth, targetImageHeight) {
        override fun onLoadCleared(placeholder: Drawable?) {
            // called when imageView is cleared. If you are referencing the bitmap 
            // somewhere else too other than this imageView clear it here
        }

        override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
            image.setImageDrawable(resource)
        }
    })

但是如果你只知道目标容器的一维而不知道图像的纵横比怎么办?您是否被迫使用原始图像尺寸?事实证明,可能有一种方法可以解决这个问题。在这种情况下,只需将您不知道的另一个维度设置为 1,Glide 会自动缩小您的图像。

imageView.viewTreeObserver.addOnGlobalLayoutListener {
    Glide.with(this)
            .load(TargetActivity.IMAGE_URL)
            .into(object : CustomTarget<Drawable>(imageView.width, 1) {
                // imageView width is 1080, height is set to wrap_content
                override fun onLoadCleared(placeholder: Drawable?) {
                    // clear resources
                }

                override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                    // bitmap will have size 1080 x 805 (original: 1571 x 1171)
                    imageView.setImageDrawable(resource)
                }
            })
}

推荐阅读