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?

8 Answers 8

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer, but note that the constructor is deprecated. Use BitmapDrawable(Resources, Bitmap) to ensure that the drawable has correctly set its target density
great, answered. should be updated due to deprecated
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

2 Comments

It's Throws Exception like android.os.NetworkOnMainThreadException
This is incorrect, @Prince see my answer using an AsyncTask to avoid NetworkOnMainThreadException.
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.

1 Comment

I seem to remember running into that problem before; I was on 1.5 at the time.
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();

Comments

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);

Comments

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)

}

Comments

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) {
           
        }
      });

Comments

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.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.