2012-07-27 134 views
0

我有一個Android應用程序從MySQL數據庫加載多個圖像到ImageButton。bitmapfactory無法加載圖像

imageButton.setImageBitmap(fetchBitmap("http://www...~.jpg")); 

我曾經能夠成功加載PNG,但現在也失敗了(沒有成功的JPG圖像)。下面是我使用的下載圖像的代碼: -

public static Bitmap fetchBitmap(String urlstr) { 
    InputStream is= null; 
    Bitmap bm= null; 
    try{ 
     HttpGet httpRequest = new HttpGet(urlstr); 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); 

     HttpEntity entity = response.getEntity(); 
     BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
     is = bufHttpEntity.getContent(); 
     BitmapFactory.Options factoryOptions = new BitmapFactory.Options(); 
     bm = BitmapFactory.decodeStream(is); 
    }catch (MalformedURLException e){ 
     Log.d("RemoteImageHandler", "Invalid URL: " + urlstr); 
    }catch (IOException e){ 
     Log.d("RemoteImageHandler", "IO exception: " + e); 
    }finally{ 
     if(is!=null)try{ 
      is.close(); 
     }catch(IOException e){} 
    } 
    return bm; 
} 

我得到這個錯誤: -

D/skia(4965): --- SkImageDecoder::Factory returned null 

我已經嘗試了各種組合的建議herehere等幾種解決方案,但它不爲我工作。我錯過了什麼嗎?圖片絕對存在於我輸入的網址中。

謝謝。

回答

0

問題是無法下載圖像,因爲保存圖像的目錄沒有「執行」權限。一旦權限被添加,該應用程序工作順利:)

0

使用下面的代碼下載圖像並存儲到位圖中,它可能會幫助你。

public static Bitmap loadBitmap(String url) { 
    Bitmap bitmap = null; 
    InputStream in = null; 
    BufferedOutputStream out = null; 

    try { 
     in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); 

     final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 
     out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); 
     out.flush(); 

     final byte[] data = dataStream.toByteArray(); 
     BitmapFactory.Options options = new BitmapFactory.Options(); 

     bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options); 
    } catch (IOException e) { 
     Log.e(TAG, "Could not load Bitmap from: " + url); 
    } finally { 
     closeStream(in); 
     closeStream(out); 
    } 

    return bitmap; 
} 
+0

什麼是IO_BUFFER_SIZE? closeStream()是否簡單地關閉連接? – gkris 2012-07-27 06:12:38

+0

什麼是副本()? – gkris 2012-07-27 06:20:41

+0

聲明私有靜態final int IO_BUFFER_SIZE = 4 * 1024;這是緩衝區的大小並刪除co​​py()。 – 2012-07-27 06:21:17