androidandroid-imageview

How can I save an image from a url?


I'm setting an ImageView using setImageBitmap with an external image url. I would like to save the image so it can be used later on even if there is no internet connection. Where and how can I save it?


Solution

  • You have to save it in SD card or in your package data, because on runtime you only have access to these. To do that this is a good example

    URL url = new URL ("file://some/path/anImage.png");
    InputStream input = url.openStream();
    try {
    //The sdcard directory e.g. '/sdcard' can be used directly, or 
    //more safely abstracted with getExternalStorageDirectory()
    File storagePath = Environment.getExternalStorageDirectory();
    OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
    try {
        byte[] buffer = new byte[aReasonableSize];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
            output.write(buffer, 0, bytesRead);
        }
    } finally {
        output.close();
    }
    } finally {
    input.close();
    }
    

    Source : How do I transfer an image from its URL to the SD card?