2015-10-26 88 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單例,這是我在開始異步任務之前首先檢查的。

這顯然不是理想的,但它現在必須做。我確定有更好的解決方案,我很樂意聽到他們,如果有人提供。

相關問題