简体   繁体   中英

Android Drawable Images from URL

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?

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 )

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

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 .

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

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.

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

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)

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM