Friday, November 16, 2012

How to download the images and to create folder to save it

 
Hi all, here we are going to learn how to view an image in ImageView that are in the form of URL and to download that image in our own created folder.
 
Here we are creating a folder to save an image in SDcard.
 
 
private class DownloadTask extends AsyncTask<String, Void, Void> {


private final ProgressDialog dialog = new ProgressDialog(ImageDownloaderActivity.this);


// can use UI thread here

protected void onPreExecute() {

this.dialog.setMessage("Loading...");

this.dialog.show();

}



// automatically done on worker thread (separate from UI thread)

protected Void doInBackground(final String... a) {


try {

Thread.sleep(100);

String url1 = imageUrls[position];

URL ulrn = new URL(url1);


HttpURLConnection con = (HttpURLConnection) ulrn

.openConnection();

InputStream is = con.getInputStream();

bmp = BitmapFactory.decodeStream(is);



int widthPx = getWindowManager().getDefaultDisplay().getWidth();

int heightPx = getWindowManager().getDefaultDisplay().getHeight();

bmp = Bitmap.createScaledBitmap(bmp, widthPx, heightPx, true);



} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 
catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}


// can use UI thread here

protected void onPostExecute(final Void unused) {


if (null != bmp) {

imageView.setImageBitmap(bmp);

}

 
else

System.out.println("The Bitmap is NULL");


File dir = new File(Environment.getExternalStorageDirectory() + "/Example/Wallpapers/");  //path of your own folder

File[] files = dir.listFiles();

if (files == null)

{

int numberOfImages = 0;

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();

Bitmap bitmap = drawable.getBitmap();

File sdCardDirectory = Environment.getExternalStorageDirectory();

new File(sdCardDirectory + "/Example/Wallpapers/").mkdirs();  //creating a folder

File image = new File(sdCardDirectory + "/Example/Wallpapers/Sample" + numberOfImages + ".JPG");          // naming your image as sample1,2,3,,..and saving it in created folder

boolean success = false;


FileOutputStream outStream;

try {

outStream = new FileOutputStream(image);

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

outStream.flush();

outStream.close();

success = true;

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {


e.printStackTrace();

}

if (success) {

Toast.makeText(getApplicationContext(),"Image saved successfully in Sdcard/Example/Wallpapers",Toast.LENGTH_LONG).show();

} else {

Toast.makeText( getApplicationContext(), "Error during image saving", Toast.LENGTH_LONG) .show();

}

}

}

No comments:

Post a Comment