Search code examples
androidimgur

Display an Image from imgur


I was able to upload a picture in Imgur and to get the link using example given in the API site. What I can't do is retrieve Bitmap or Drawable from URL. And I find no documentation about it.

URL url= "http://imgur.com/1awAsRh"
Bitmap mPic = BitmapFactory.decodeStream(url.openConnection().getInputStream());

mPic is null.

I see that the image url on the site is https://i.sstatic.net/zDlBm.jpg I see the picture can be png jpg etc...

Is there a way to get direct Image URL, is it always the same pattern?

Tx in advance!


Solution

  • Try using this, which implements an AsyncTask to do stuff in the background (needed for Android 4.0+):

    class loadimage extends AsyncTask<Void, Void, Void> {
        ProgressDialog pdLoading = new ProgressDialog(YourClass.this);
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("Loading Image...");
            pdLoading.show();
        }
    
        @Override
        protected void doInBackground(Void... params) {
            String stringurl = "http://imgur.com/1awAsRh"
            try {
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(stringurl).getContent());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pdLoading.dismiss();
            // do what you want with your bitmap
            return null;
        }
    }
    

    And then call it like this in your onCreate:

    new loadimage().execute();
    

    You also need to make sure you have this in your manifest:

    <uses-permission android:name="android.permission.INTERNET" />