2010-08-13 79 views
3

我在android中使用webview來顯示圖像(主要是使用谷歌ajax API),現在如果我想將圖像保存到本地存儲,我該怎麼辦?我有圖像網址,可用於保存。保存圖像,webview,android

回答

2

如果你有圖片網址,這是很容易的。你只需要檢索圖像的字節。下面是一個示例,應該幫助你:

try { 
    URL url = new URL(yourImageUrl); 
    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); 
    } 
    return output.toByteArray(); 
} catch (MalformedURLException e) { 
e.printStackTrace(); 
return null; 
} catch (IOException e) { 
e.printStackTrace(); 
return null; 
} 

這將返回您可以儲存任何你喜歡的ByteArray,或重用創建圖像,通過這樣做:

Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); 
+0

謝謝,我從事類似的工作,我能夠保存圖像,我使用File對象指定存儲圖像的路徑。 – sat 2010-08-21 10:56:10

+0

做得好。的確,你可以從其他來源加載圖像。 – Sephy 2010-08-21 11:02:52

+0

我以更簡單的方式製作了它: Bitmap image = BitmapFactory.decodeStream((InputStream)new URL(「Http Where your Image is」)。getContent()); – 2014-04-04 03:22:14

0

我知道這是一個很老,但這是有效的太:

Bitmap image = BitmapFactory.decodeStream((InputStream) new URL("Http Where your Image is").getContent()); 

充滿了位圖,只是這樣做,以節省存儲(感謝https://stackoverflow.com/a/673014/1524183

FileOutputStream out; 
try { 
     out = new FileOutputStream(filename); 
     image.compress(Bitmap.CompressFormat.PNG, 90, out); 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
     try{ 
      out.close(); 
     } catch(Throwable ignore) {} 
} 

IHMO比公認的答案更清潔和更簡單。

+0

創建位圖對象圖像拋出錯誤。 – Aashish 2018-03-09 12:55:38