【问题标题】:Download image and resize to avoid OOM errors, Picasso fit() distorts image下载图像并调整大小以避免OOM错误,Picasso fit() 扭曲图像
【发布时间】:2015-05-03 06:54:57
【问题描述】:

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

// 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 虚拟机的手机上,我遇到了内存不足的问题。所以我尝试将(2)更改为:

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

这导致图像失真。由于在下载图像之前我不知道图像的尺寸,因此我无法设置 ImageView 尺寸,因此在调整图像大小时不考虑我的 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()

我假设转换在这种情况下没有帮助,因为public Bitmap transform(Bitmap source) 的输入已经有很大的位图,这会导致我内存不足。

【问题讨论】:

    标签: android-image picasso


    【解决方案1】:

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

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

    【讨论】:

    • 这行得通!我被文档甩了,这让我认为 centerInside() 需要与 resize() From Doc 一起使用:Centers an image inside of the bounds specified by resize(int, int). This scales the image so that both dimensions are equal to or less than the requested bounds.
    • 我知道,这是一个常见错误,文档对此并不清楚。仅供参考,fit() 只是等待视图获取其尺寸,但实际上没有将图像缩放到该尺寸
    • fit()Attempt to resize the image to fit exactly into the target ImageView's bounds. 那么它不是缩放位图吗?你最后的评论让我有点困惑。我想确保完成下采样并加载正确大小的位图以避免浪费内存。做这个的最好方式是什么?顺便说一句,我的应用程序中有另一个 View,它具有固定的 NxN 尺寸,我使用 fit()centerCrop() 假设会发生下采样。
    • 是的,它确实使用View 大小对原始图像进行下采样。但是纵横比呢?如果你有一个方形的View 和一个矩形的图像,毕加索不知道该怎么办。这就是为什么您需要将fit() 与其他两个之一结合起来。现在清楚了吗?
    • 是的,明白了!当fit()centerInside() 一起使用时,毕加索将进行正确的下采样以适应View 并调整纵横比。 centerCrop() 可用于确保图像填满整个View,并且在将矩形图像放入正方形View 的情况下,它将裁剪图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多