保存图像,webview,android

问题描述:

我在android中使用webview来显示图像(主要是使用谷歌ajax API),现在如果我想将图像保存到本地存储,我该怎么办?我有图像网址,可用于保存。保存图像,webview,android

如果你有图片网址,这是很容易的。你只需要检索图像的字节。下面是一个示例,应该帮助你:

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

我知道这是一个很老,但这是有效的太:

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