Download and Display Image in Android

When you want to download a Image from the Web and Display it in Android in a ImageView i encountered two different approaches:

1. Download the Image and Display it:

Drawable DownloadDrawable(String url, String src_name) throws java.io.IOException {
	return Drawable.createFromStream(((java.io.InputStream) new java.net.URL(url).getContent()), src_name);
}
 
[...]
 
try {
	Drawable drw = DownloadDrawable("http://www.google.de/intl/en_com/images/srpr/logo1w.png", "src")
	ImageView1.setImageDrawable(drw);
} catch (IOException e) {
	// Something went wrong here
}

2. Dowload the Image, Save it to “Hard-Disk” and load it later to Display it.

public static void DownloadFile(String imageURL, String fileName) throws IOException {
	URL url = new URL(imageURL);
	File file = new File(fileName);
 
	long startTime = System.currentTimeMillis();
	Log.d("DownloadFile", "Begin Download URL: " + url + " Filename: " + fileName);
	URLConnection ucon = url.openConnection();
	InputStream is = ucon.getInputStream();
	BufferedInputStream bis = new BufferedInputStream(is);
	ByteArrayBuffer baf = new ByteArrayBuffer(50);
	int current = 0;
	while ((current = bis.read()) != -1)
		baf.append((byte) current);
	FileOutputStream fos = new FileOutputStream(file);
	fos.write(baf.toByteArray());
	fos.close();
	Log.d("DownloadFile", "File was downloaded in: " + ((System.currentTimeMillis() - startTime) / 1000) + "s");
}
 
[...]
 
try {
	String imagePath = getFilesDir() + "/" + "logo1w.png";
	DownloadFile("http://www.google.de/intl/en_com/images/srpr/logo1w.png", imagePath);
} catch (IOException e) {
	// Something went wrong here
}
 
ImageView1.setbMap(BitmapFactory.decodeFile(imagePath));

I used getFilesDir() to obtain the Path where i can Save the Image, So for example the Path could be: “/data/data/org.android.downloadimage/files/logo1w.png”

When you only need to display a image once you should just go for 1. but if you need to Display the same Image over and Over again it would be a waste of Bandwith and therefore expensive Traffic for the User, then you should stick with 2.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.