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();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);

return myBitmap;
} catch (IOException e) {
e.printStackTrace();
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() {
@Override
public void run() {
Bitmap getdownload = downloadBitmap("http://lh5.ggpht.com/_hepKlJWopDg/TB-_WXikaYI/AAAAAAAAElI/715k4NvBM4w/s144-c/IMG_0075.JPG");
Log.e("", getdownload.getWidth()+" "+getdownload.getHeight());
}
});
t.start();

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

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

Comments

Popular posts from this blog

Play video inside OpenGL ES by using MediaCodec