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
  • 15,395
  • 32
  • 113
  • 196
Señor Reginold Francis
  • 16,318
  • 16
  • 57
  • 73

8 Answers8

50

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
  • 788
  • 1
  • 13
  • 15
Felipe
  • 16,649
  • 11
  • 68
  • 92
  • 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
16

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
  • 179,855
  • 19
  • 132
  • 245
Señor Reginold Francis
  • 16,318
  • 16
  • 57
  • 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
  • 85,990
  • 32
  • 182
  • 176
3

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
  • 124,308
  • 23
  • 334
  • 268
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
  • 16,245
  • 11
  • 62
  • 79
1

Kotlin Solution With Coil

fun convertUrlToDrawable(url: String, result: (Drawable) -> Unit) {
val loader = ImageLoader(context = appContext)
val req = ImageRequest.Builder(appContext)
    .allowHardware(true)
    .allowConversionToBitmap(true)
    .data(url) // demo link
    .target { drawable ->
        result(drawable)
    }
    .build()
loader.enqueue(req)

}

abhi
  • 961
  • 9
  • 13
1

You can use Glide to load your imageURL as Drawable and then reuse it wherever needed.
Here's how to implement this strategy:

Glide.with(ctx)
      .asDrawable()
      .load(mImageURL)
      .into(new CustomTarget<Drawable>() {
        @Override
        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
           // Your imageURL is now converted to a drawable 'resource'
        }

        @Override
        public void onLoadCleared(@Nullable Drawable placeholder) {
           
        }
      });
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,870
  • 5
  • 45
  • 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