Android - Save image from URL onto SD card

后端 未结 7 1345
太阳男子
太阳男子 2020-11-28 07:37

I want to save an image from a URL to the SD card (for future use) and then load that image from the SD card to use it as a drawable overlay for Google maps.

Here is

7条回答
  •  猫巷女王i
    2020-11-28 08:30

    Try this code to save the Image from the URL to SDCard.

    URL url = new URL ("file://some/path/anImage.png"); 
    InputStream input = url.openStream(); 
    try {     
        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(); 
    }
    

    If you want to create a sub directory on the SD card use:

    File storagePath = new File(Environment.getExternalStorageDirectory(),"Wallpaper");
    storagePath.mkdirs();
    

    To create a the sub directory "/sdcard/Wallpaper/".

    Hope it will help you.

    Enjoy. :)

提交回复
热议问题