Search...

Sunday, November 13, 2011

How to download image from url and convert to drawable in android


Pass the absolute path of the image location in the below method.
public static Drawable downloadImage(String loc) {

try {
URLConnection connection = new URL(loc).openConnection();
InputStream stream = connection.getInputStream();
BufferedInputStream in = new BufferedInputStream(stream);
ByteArrayOutputStream out = new ByteArrayOutputStream(50000);
int read;
byte[] b = new byte[50000];
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
out.flush();
out.close();
byte[] raw = out.toByteArray();
Drawable d = new BitmapDrawable(new ByteArrayInputStream(raw));

return d;
} catch (Exception e) {

return null;
}

No comments:

Post a Comment