下载图像并调整大小以避免OOM错误,Picasso fit()会使图像失真 [英] Download image and resize to avoid OOM errors, Picasso fit() distorts image

查看:182
本文介绍了下载图像并调整大小以避免OOM错误,Picasso fit()会使图像失真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以全屏视图并使用以下代码显示图像:

I am trying to show images in a full screen view and using the following code:

// Target to write the image to local storage.
Target target = new Target() {
   // Target implementation.
}

// (1) Download and save the image locally.
Picasso.with(context)
       .load(url)
       .into(target);

// (2) Use the cached version of the image and load the ImageView.
Picasso.with(context)
       .load(url)
       .into(imgDisplay);

此代码在较新的手机上效果很好,但是在具有32MB VM的手机上,我遇到了内存不足的问题.所以我尝试将(2)更改为:

This code works well on newer phones, but on phones with 32MB VMs, I get out of memory issues. So I tried changing (2) to:

    Picasso.with(context)
       .load(url)
       .fit()
       .into(imgDisplay);

这导致图像失真.由于在下载图像之前我不知道图像的尺寸,因此无法设置ImageView的尺寸,因此在调整图像大小时,无需考虑ImageView的宽高比:

This resulted in distorted images. Since I do not know the dimensions of the image until it is downloaded, I cannot set the ImageView dimensions, and hence the image is being resized without any consideration to aspect ratio in to my ImageView:

    <ImageView
    android:id="@+id/imgDisplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitCenter"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

处理这种情况的最佳方法是什么?我的原始图像的最大宽度为768,高度为1024,并且当屏幕远小于此尺寸时,我想降低采样率.如果尝试使用resize(),我的代码将变得很复杂,因为我必须等待(1)完成下载,然后在(2)中添加resize().

What is the best way to handle this situation? My original images have max width 768, and height 1024, and I want to downsample when the screens are much smaller than this. If I try to use resize(), my code becomes complicated, as I have to wait for (1) to finish the download and then add the resize() in (2).

我假设在这种情况下转换无济于事,因为public Bitmap transform(Bitmap source)的输入将已经具有较大的位图,这将导致我内存不足.

I am assuming Transformations do not help in this case, as the input to public Bitmap transform(Bitmap source) will already have the large bitmap which will cause me to run out of memory.

推荐答案

您可以将fit()centerCrop()centerInside()结合使用,具体取决于您希望图像如何适合View:

You can combine fit() with centerCrop() or centerInside(), depending on how you want the image to fit your View:

Picasso.with(context)
   .load(url)
   .fit()
   .centerCrop()
   .into(imgDisplay);

Picasso.with(context)
   .load(url)
   .fit()
   .centerInside()
   .into(imgDisplay);

这篇关于下载图像并调整大小以避免OOM错误,Picasso fit()会使图像失真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆