Download image and resize to avoid OOM errors, Picasso fit() distorts image

半城伤御伤魂 提交于 2019-12-19 19:06:27

问题


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);

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);

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" />

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).

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.


回答1:


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);


来源:https://stackoverflow.com/questions/30011106/download-image-and-resize-to-avoid-oom-errors-picasso-fit-distorts-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!