Thursday, 31 May 2012

Android: creating a Drawable or a Bitmap from a web url

Here are a couple of methods for creating a Drawable or a Bitmap from a web url:

/** Returns a Drawable object containing the image located at 'imageWebAddress' if successful, and null otherwise.
 * (Pre: 'imageWebAddress' is non-null and non-empty;
 * method should not be called from the main/ui thread.)*/
public static Drawable createDrawableFromUrl(String imageWebAddress)
{
  Drawable drawable = null;

  try
  {
    InputStream inputStream = new URL(imageWebAddress).openStream();
    drawable = Drawable.createFromStream(inputStream, null);
    inputStream.close();
  }
  catch (MalformedURLException ex) { }
  catch (IOException ex) { }

  return drawable;
}

/** Returns a Bitmap object containing the image located at 'imageWebAddress'
 * if successful, and null otherwise.
 * (Pre: 'imageWebAddress' is non-null and non-empty;
 * method should not be called from the main/ui thread.)*/
public static Bitmap createBitmapFromUrl(String imageWebAddress)
{
  Bitmap bitmap = null;

  try
  {
    InputStream inputStream = new URL(imageWebAddress).openStream();
    bitmap = BitmapFactory.decodeStream(inputStream);
    inputStream.close();
  }
  catch (MalformedURLException ex) { }
  catch (IOException ex) { }

  return bitmap;
}

No comments: