毕加索在加载图像时内存不足 [英] Picasso gives out of memory when load an image

查看:100
本文介绍了毕加索在加载图像时内存不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Picasso从服务器加载图像并将其显示在ImageView中.

I am using Picasso to load images from my server and display them in ImageView.

我观察到用户手机的一些崩溃报告,当毕加索试图将图像加载到ImageView中时,发生了内存不足异常".

I observes some crash reports from user's phone where Out of Memory Exception happens when Picasso is trying to load an image into ImageView.

堆栈跟踪如下:

java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:596)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:832)
at android.content.res.Resources.loadDrawable(Resources.java:2988)
at android.content.res.Resources.getDrawable(Resources.java:1558)
at android.widget.ImageView.resolveUri(ImageView.java:646)
at android.widget.ImageView.setImageResource(ImageView.java:375)
at com.squareup.picasso.PicassoDrawable.setPlaceholder(PicassoDrawable.java:62)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:520)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:462)
at com.mycompany.myAdapter.getView(MyAdapter.java:102)
at android.widget.AbsListView.obtainView(AbsListView.java:2608)
at android.widget.GridView.makeAndAddView(GridView.java:1346)

MyAdapter.java:102附近的代码如下:

The Code near MyAdapter.java:102 as below:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

    .....Some code .....

    Picasso.with(mContext)
    .load(url_to_server)
    .placeholder(R.drawable.default_placeholder)
    .into(holder.imageItem);  // Line 102

    .....Some code .....

    return convertView;
    }

我使用此库的方式有问题吗?

Is there sth wrong with the way I use this library?

推荐答案

要加载图标或启动器之类的小图像,我们可以使用.setImageResource(image).但是,加载大图像最好使用Picasso并获得简单性的好处.和本地缓存.

To load small images like icons o launchers we can use .setImageResource(image) However, to load big images is better to use Picasso and get the benefit of simplicity and local caching.

根据文档正确设置毕加索是必要的:

It is necesary to setup Picasso properly according to the documentation:

在加载到ImageView之前,请确保使用fit()调整图像的大小.否则,如果渲染大量图片,则会消耗额外的内存,滚动缓慢或遇到内存不足的问题."

"Be sure to use fit() to resize the image before loading into the ImageView. Otherwise, you will consume extra memory, experience sluggish scrolling, or encounter out of memory issues if you render a lot of pictures".

if (imageUri != null && !imageUri.isEmpty()) {
   Picasso.with(context).load(imageUri)
  .fit().centerCrop()
  .placeholder(R.drawable.user_placeholder)
  .error(R.drawable.user_placeholder_error)
  .into(imageView);
}

这篇关于毕加索在加载图像时内存不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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