31

I am presently using the following piece of code to load in images as drawable objects form a URL.

Drawable drawable_from_url(String url, String src_name) 
throws java.net.MalformedURLException, java.io.IOException {
        return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);

}

This code works exactly as wanted, but there appears to be compatibility problems with it. In version 1.5, it throws a FileNotFoundException when I give it a URL. In 2.2, given the exact same URL, it works fine. The following URL is a sample input I am giving this function.

http://bks6.books.google.com/books?id=aH7BPTrwNXUC&printsec=frontcover&img=1&zoom=5&edge=curl&sig=ACfU3U2aQRnAX2o2ny2xFC1GmVn22almpg

How would I load in images in a way that is compatible across the board from a URL?

nbro
  • 13,796
  • 25
  • 99
  • 185
Señor Reginold Francis
  • 15,278
  • 16
  • 55
  • 73

6 Answers6

51

Bitmap is not a Drawable. If you really need a Drawable do this:

public static Drawable drawableFromUrl(String url) throws IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return new BitmapDrawable(Resources.getSystem(), x);
}

(I used the tip found in https://stackoverflow.com/a/2416360/450148)

Joonsoo
  • 730
  • 1
  • 11
  • 13
Felipe
  • 16,504
  • 10
  • 65
  • 88
  • 1
    Great answer, but note that the constructor is deprecated. Use BitmapDrawable(Resources, Bitmap) to ensure that the drawable has correctly set its target density – avalancha Nov 11 '15 at 08:21
  • great, answered. should be updated due to deprecated – mochadwi Feb 19 '19 at 14:17
15

Solved it myself. I loaded it in as a bitmap using the following code.

Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {

    HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
    connection.setRequestProperty("User-agent","Mozilla/4.0");

    connection.connect();
    InputStream input = connection.getInputStream();

    return BitmapFactory.decodeStream(input);
}

It was also important to add in the user agent, as googlebooks denies access if it is absent

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Señor Reginold Francis
  • 15,278
  • 16
  • 55
  • 73
5

I'm not sure, but I think that Drawable.createFromStream() is more intended for use with local files rather than downloaded InputStreams. Try using BitmapFactory.decodeStream(), then wrapping the return Bitmap in a BitmapDrawable.

Dan Lew
  • 83,807
  • 30
  • 180
  • 174
2

To get a Drawable image from an URL you must use an AsyncTask to avoid NetWorkOnMainThreadException, and the result Drawable obtained in onPostExecute() you can set to your ImageView:

    final String urlImage = "https://www.android.com/static/2016/img/hero-carousel/banner-android-p-2.jpg";

    new AsyncTask<String, Integer, Drawable>(){

        @Override
        protected Drawable doInBackground(String... strings) {
            Bitmap bmp = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(urlImage).openConnection();
                connection.connect();
                InputStream input = connection.getInputStream();
                bmp = BitmapFactory.decodeStream(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new BitmapDrawable(bmp);
        }

        protected void onPostExecute(Drawable result) {

            //Add image to ImageView
            myImageView.setImageDrawable(result);

        }


    }.execute();
Jorgesys
  • 119,885
  • 23
  • 317
  • 256
1

The following code works for me:

Matrix Mat = new Matrix();

Bitmap Source = BitmapFactory.decodeFile("ItemImagePath");

Bitmap Destination = Bitmap.createScaledBitmap( Source, 320, 320, true );

Source = Bitmap.createBitmap( Destination, 0, 0, Destination.getWidth(), Destination.getHeight(),Mat, true );

ItemImageView.setImageBitmap(Source);
Aziz Shaikh
  • 15,647
  • 11
  • 58
  • 78
0

You can use com.androidquery.AndroidQuery to do this quite simply. For example:

AQuery aq = new AQuery(this);
aq.id(view).image("http://yourserver/yourimage.png", true, true, 300, new BitmapAjaxCallback() {
        @Override
        public void callback(String url, ImageView imageView, Bitmap bitmap, AjaxStatus status) {
            Drawable drawable = new BitmapDrawable(getResources(), bm);
        }
    });

If you use the BitmapAjaxCallback you will get access to the BitMap which you can wrap as a BitmapDrawable.

Adriaan Koster
  • 15,325
  • 4
  • 44
  • 60
  • The person asked for some way to create a drawable from an url,yours one is doing that underneath,no way of getting the **drawable**;rather you pass a view and the library sets the image on it which is downloaded from the url.So how it can be considered to be an answer for the question? – Munim Oct 22 '13 at 06:42