2014-07-22 47 views
0

我有從一個url加載一個png文件到一個ByteArrayOutputStream的代碼。現在我想將它製作成位圖,以便繪製它。我試過 位圖bBack = BitmapFactory.decodeStream(輸出);;但是,BitMapFactory不會接收yteArrayOutputStream。試圖從一個ByteArrayOutputStream創建一個位圖

我怎樣才能創造從一個ByteArrayOutputStream對象的位圖? 代碼

try { 
    URL url = new URL("http://stage.master.embryooptions.healthbanks.com/siteassets/24/ShadyGrove-logo.png"); 
    InputStream is = (InputStream) url.getContent(); 
    byte[] buffer = new byte[8192]; 
    int bytesRead; 
    ByteArrayOutputStream output = new ByteArrayOutputStream(); 
    while ((bytesRead = is.read(buffer)) != -1) { 
     output.write(buffer, 0, bytesRead); 
    } 

///////////////////////////////////////////////////////////////////////////// 
// HOW DO I GET A BITMAP????????? 
/////////////////////////////////////////////////////////////////////////////// 
//     Bitmap bBack=BitmapFactory.decodeStream(output); 
    return ""; 
} catch (MalformedURLException e) { 
        e.printStackTrace(); 
    return null; 
} catch (IOException e) { 
    e.printStackTrace(); 
    return null; 
} 

回答

1

如果你的目標是創建從您的網址下載圖像的位圖對象,然後ByteArrayOutputStream是沒有必要的。所有你需要的是這樣的:

InputStream is = (InputStream) url.getContent(); 
Bitmap image = BitmapFactory.decodeStream(is); 

你可以看一下爲BitmapFactory開發者頁面獲取更多信息。

+0

+1更好的替代方案 – Devrim

2

下面應該爲你工作:

byte[] bitmapData = output.toByteArray(); 
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData , 0, bitmapData.length); 

注:要對位圖裝載小心。解碼到位圖時始終使用BitmapFactory.Options以防止與內存有關的錯誤。

Read more.