How can I save an image from a url?

后端 未结 5 1121
情深已故
情深已故 2020-12-17 05:53

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 interne

5条回答
  •  时光说笑
    2020-12-17 06:15

    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?

提交回复
热议问题