Thursday, July 25, 2013

Download image as Bitmap

Sometimes, we need to download image and show to ImageView.
Therefore, it needs some Http API to do so.
Below is the code of how to download image using Http API and set it as Bitmap.

Bitmap downloadBitmap(String link) {
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);

return myBitmap;
} catch (IOException e) {
Log.e("getBmpFromUrl error: ", e.getMessage().toString());
return null;

To use it, you NEED to create a thread because it is restricted on using Http on UI thread.

Thread t = new Thread(new Runnable() {
public void run() {
Bitmap getdownload = downloadBitmap("");
Log.e("", getdownload.getWidth()+" "+getdownload.getHeight());

At last, don't forget to set INTERNET permission.

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

No comments:

Post a Comment