2015-10-26 85 views
0

目前我从一个url加载图片,并且它正在走向漫长,我无法弄清楚为什么,有时需要超过60秒的时间才能获得并非真正的图片那很大。Android图片需要很长时间才能从URL中获取

我的代码:

获取图像异步任务:

public class GetImageAsyncTask extends AsyncTask<Void, Void, Bitmap> { 

String url; 
OnImageRetrieved listener; 
ImageView imageView; 
int height; 
int width; 

public GetImageAsyncTask(String url, ImageView imageView,OnImageRetrieved listener, int height, int width) { 
    this.url = url; 
    this.listener = listener; 
    this.imageView = imageView; 
    this.height = height; 
    this.width = width; 
} 

public interface OnImageRetrieved { 
    void onImageRetrieved(Bitmap image, ImageView imageview, String url); 
} 

protected Bitmap doInBackground(Void... params) { 

    Bitmap image = null; 

    try { 
     image = ImageUtilities.decodeSampledBitmapFromUrl(this.url, this.width, this.height); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return image; 
} 

    protected void onPostExecute(Bitmap result) { 
     this.listener.onImageRetrieved(result, this.imageView, this.url); 
    } 
} 

public static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight) throws IOException { 

    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 

    BitmapFactory.decodeStream(new java.net.URL(url).openStream(), null, options); 

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    options.inJustDecodeBounds = false; 

    return BitmapFactory.decodeStream(new java.net.URL(url).openStream(), null, options); 
} 

获得试样尺寸:

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 

    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     final int halfHeight = height/2; 
     final int halfWidth = width/2; 

     while ((halfHeight/inSampleSize) > reqHeight 
       && (halfWidth/inSampleSize) > reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 

使用这些方法,因为如果没有可能出现内存并发症,但似乎需要的时间只是漫长而已。有没有很重的计算,我只是没有看到或?

+0

因此他们在服务器端有多大? 'options.outHeight'和'options.outWidth'的价值是什么? – pskink

+0

s3上的图像范围从300到1100kb,所以我的意思是,不完全是巨大的。 宽度可以在500-2000之间的任何位置,高度400〜1200 认为香港专业教育学院遇到另外一个问题,我的适配器getView获取调用方式很多次这是导致字面上100的电话我getIMageAsyncTask –

回答

1

你可以使用毕加索或volly库来加载图像。我建议使用它,因为它是由google本身引入的。

+0

林纪念这一正确的,因为老实说毕加索已经救了我10几个小时,我不知道是什么让它很难处理android burt picasso中的图像,这绝对解决了这个问题。 –

0

所以这个问题来自于数组适配器,并且getView()可以被称为100次,可以接近100mb的数据被同时下载。

所以作为这种情况的临时修复,我实现了一个全局的LruCache单例,这是我在开始异步任务之前首先检查的。

这显然不是理想的,但它现在必须做。我确定有更好的解决方案,我很乐意听到他们,如果有人提供。

相关问题