Saving image, webview, android

后端 未结 2 1967
情深已故
情深已故 2020-12-10 20:40

I am using webview in android to display images (mainly using google ajax API), Now if I want to save an image into local storage, How do I do ? I have image url, which can

相关标签:
2条回答
  • 2020-12-10 21:06

    I know this is a quite old but this is valid too:

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

    With the Bitmap filled up, just do this to save to storage (Thanks to 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 much more cleaner and simpler than the accepted answer.

    0 讨论(0)
  • 2020-12-10 21:07

    If you have the image url, this is dead easy. You just have to retrieve the bytes of the image. Here is a sample that should help you :

    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;
    }
    

    This will return a byteArray that you can either store wherever you like, or reuse to create an image, by doing that :

    Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    
    0 讨论(0)
提交回复
热议问题