Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Save image from URL onto SD card

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 the save section of the function:

//SAVE TO FILE

String filepath = Environment.getExternalStorageDirectory().getAbsolutePath(); 
String extraPath = "/Map-"+RowNumber+"-"+ColNumber+".png";
filepath += extraPath;

FileOutputStream fos = null;
fos = new FileOutputStream(filepath); 

bmImg.compress(CompressFormat.PNG, 75, fos);

//LOAD IMAGE FROM FILE
Drawable d = Drawable.createFromPath(filepath);
return d;

The image is saved to the sd card succuessfully but fails when getting to the createFromPath() line. I don't understand why it would save ok to that destination but not load from it....

like image 451
Jamie Avatar asked Feb 02 '11 13:02

Jamie


3 Answers

Try this code.It works...

try
{   
  URL url = new URL("Enter the URL to be downloaded");
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true);                   
  urlConnection.connect();                  
  File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
  String filename="downloadedFile.png";   
  Log.i("Local filename:",""+filename);
  File file = new File(SDCardRoot,filename);
  if(file.createNewFile())
  {
    file.createNewFile();
  }                 
  FileOutputStream fileOutput = new FileOutputStream(file);
  InputStream inputStream = urlConnection.getInputStream();
  int totalSize = urlConnection.getContentLength();
  int downloadedSize = 0;   
  byte[] buffer = new byte[1024];
  int bufferLength = 0;
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
  {                 
    fileOutput.write(buffer, 0, bufferLength);                  
    downloadedSize += bufferLength;                 
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
  }             
  fileOutput.close();
  if(downloadedSize==totalSize) filepath=file.getPath();    
} 
catch (MalformedURLException e) 
{
  e.printStackTrace();
} 
catch (IOException e)
{
  filepath=null;
  e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
like image 75
Giridharan Avatar answered Nov 07 '22 06:11

Giridharan


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. :)

like image 6
Shreyash Mahajan Avatar answered Nov 07 '22 07:11

Shreyash Mahajan


I also faced the same issue and resolved mine with this. Try this

private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
        {
            @Override
            protected Bitmap doInBackground(String... arg0) 
            {           
                downloadImagesToSdCard("","");
                return null;
            }

               private void downloadImagesToSdCard(String downloadUrl,String imageName)
                {
                    try
                    {
                        URL url = new URL(img_URL); 
                        /* making a directory in sdcard */
                        String sdCard=Environment.getExternalStorageDirectory().toString();     
                        File myDir = new File(sdCard,"test.jpg");

                        /*  if specified not exist create new */
                        if(!myDir.exists())
                        {
                            myDir.mkdir();
                            Log.v("", "inside mkdir");
                        }

                        /* checks the file and if it already exist delete */
                        String fname = imageName;
                        File file = new File (myDir, fname);
                        if (file.exists ()) 
                            file.delete (); 

                             /* Open a connection */
                        URLConnection ucon = url.openConnection();
                        InputStream inputStream = null;
                        HttpURLConnection httpConn = (HttpURLConnection)ucon;
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();

                          if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                          {
                           inputStream = httpConn.getInputStream();
                          }

                            FileOutputStream fos = new FileOutputStream(file);  
                int totalSize = httpConn.getContentLength();
                        int downloadedSize = 0;   
                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        while ( (bufferLength = inputStream.read(buffer)) >0 ) 
                        {                 
                          fos.write(buffer, 0, bufferLength);                  
                          downloadedSize += bufferLength;                 
                          Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
                        }   

                            fos.close();
                            Log.d("test", "Image Saved in sdcard..");                      
                    }
                    catch(IOException io)
                    {                  
                         io.printStackTrace();
                    }
                    catch(Exception e)
                    {                     
                        e.printStackTrace();
                    }
                }           
        } 

Declare your network operations in AsyncTask as it will load it as a background task. Don't load network operation on main thread. After this either in button click or in content view call this class like

 new ImageDownloadAndSave().execute("");

And don't forget to add the nework permission as:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

Hope this may help someone :-)

like image 4
AndroidOptimist Avatar answered Nov 07 '22 07:11

AndroidOptimist