Upload image on Imgur account with user authentication in Phimpme

In Phimpme app we wanted to allow a user to upload an image into their personal Imgur account. To achieve this I have to authenticate the user Imgur account in our Phimpme android app and upload the image to their account. In this post, I will be explaining how to upload an image on Imgur from Phimpme Android app from user account using authentication token.

Let’s get started

Step – 1: Register your application on Imgur to receive your Client ID and Client Secret.

Register your application on Imgur from here and obtain the Client-Id and Client-Secret. Client-Id will be used to authenticate user account.

Step-2: Authenticate the user

Well, This is the tedious task as they haven’t provided any direct API for Java/Android or any other language to authenticate. So, I achieved it via WebView of Android, in  Phimpme app we asked user to login into their WebView and the we intercepted network calls and parsed URL to get the access token once the user logged in.

a.) Load below URL in WebView with your application’s client id.

https://api.imgur.com/oauth2/authorize?client_id=ClientId&response_type=token&state=APPLICATION_STATE

WebView imgurWebView = (WebView) findViewById(R.id.LoginWebView);
imgurWebView.setBackgroundColor(Color.TRANSPARENT);
imgurWebView.loadUrl(IMGUR_LOGIN_URL);
imgurWebView.getSettings().setJavaScriptEnabled(true);

imgurWebView.setWebViewClient(new WebViewClient() {
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {

      if (url.contains(REDIRECT_URL)) {
          splitUrl(url, view);
      } else {
          view.loadUrl(url);
      }

      return true;
  }


b.)  Now, It will ask the user to enter the Imgur username and password after that it will redirect to the URL, which we added as a callback URL while adding our app in Imgur dashboard. In Phimpme I added https://org.fossaisa.phimpme as callback URL.

c.)  After logging in WebView it will redirect to the callback URL with the following parameters: access_token, refresh_token, authorization_code:

https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=REQUESTED_RESPONSE_TYPE&state=APPLICATION_STATE

Step -3

To obtain the access token from the right URL we have to intercept each and every URL is getting loaded in webview and detect the right URL and parse it. For which I have overridden the shouldOverrideUrlLoading of webViewclient and pass on it to splitUrl method.

private void splitUrl(String url, WebView view) {
  String[] outerSplit = url.split("\\#")[1].split("\\&");
  String username = null;
  String accessToken = null;

  int index = 0;

  for (String s : outerSplit) {
      String[] innerSplit = s.split("\\=");

      switch (index) {
          // Access Token
          case 0:
              accessToken = innerSplit[1];
              break;

          // Refresh Token
          case 3:
              refreshToken = innerSplit[1];
              break;

          // Username
          case 4:
              username = innerSplit[1];
              break;
          default:

      }

      index++;
  }

Now we have user access token of the user to access API to Imgur to do operations(read, write) for that particular user.

Note: Authentication token is valid for 28 days only, after 28 days you will have to get the new access token.

Step- 4: Upload image using authentication token

Now we are ready to upload images on Imgur on the behalf of user’s account and to upload we need to send requests to Imgur API to this URL with authentication header and body image. The body will contain the imageString, title and description.

When we post image on Imgur anonymously, we need to add header as Authorization Client-Id {client-id} but to upload image on imgur from an account, we need to add header Authorization Bearer with value equals to access-token and image data in base64 string as request body, as we did in our previous post on upload image on Imgur.

Imgur Account Image uploads

That’s it.

The problem I faced:

I have noticed that one token is valid for 28 days only, so after 28 you will need to ask the user to log in again in Imgur app.

To avoid this what I did is before 28 days I do send a request to get a new access token which is again valid for next 28 days.

Resources:

Continue ReadingUpload image on Imgur account with user authentication in Phimpme

Upload Image to Imgur Anonymously Using Volley in Phimpme Android app

As Phimpme Android is an image app in which lets you share your image on multiple platform without installing that apps like Twitter, Facebook, Pinterest and Imgur. Imgur is the best place to share and enjoy the most awesome images on the Internet. Imgur provides APIs to  upload image from your account as well as anonymously. In this blog I am going to explain how I added the imgur upload feature in Phimpme Android app.

I have implemented upload to  Imgur anonymously. There is step by step guide to implementing it.

Step 1: Register your application on Imgur.

To register your application click here, For more detail read their documentation here Imgur API site.

Once you have registered your application, you will be provided with two keys, Client ID and Client Secret. Save them, we will need them later to upload an image and for = authentication purposes.

Step-2: Add a networking library in your Gradle, I have used volley.

Olley is a good networking library, works well for both API requests and File upload. To add volley in the project, add the following dependency

'com.android.volley:volley:1.0.0'

Step-3 Convert your image into the desired format to upload.

Imgur three kinds of images: A binary file, base64 data, or  URL of an image. (Up to 10MB).

In phimpme Android, we are uploading base64 image string.

So, we have to first convert our image to the bitmap and then convert the bitmap to base64. I recommend using an Image library to decode bitmap otherwise, there are chances of OutOfMemory exception thrown for large image files.

To convert bitmap to base64 string

public static String get64BaseImage (Bitmap bmp) {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
       byte[] imageBytes = baos.toByteArray();
       return Base64.encodeToString(imageBytes, Base64.DEFAULT);
   }

Best practice to add such methods into theutility class. Also, you can apply the image compression in above if you want to reduce the image size, here number 100 represents, preserve the  100% quality of the image.

Step-4:  Now we need 2 things, add image string in body and add AUTHENTICATION key in headers of the request.

We have added two methods to do above mentioned tasks.

  1. To upload the image data to Imgur.
  2. To add a header in our network request.

The header is required for Imgur to authenticate the client who uploads the file and your authentication key is your  CLIENT-ID, which we have generated in step 1.

@Override
               protected Map<String, String> getParams() throws AuthFailureError {
                   Map<String, String> parameters = new HashMap<String, String>();
                   parameters.put("image", imageString);
                   if(caption!=null && !caption.isEmpty())
                       parameters.put("title",caption);
                   return parameters;
               }


Now add the headers to authenticate the client.The above code contains the body part with the key as “image” and value as the imageString data, which was the result of get64BaseImage () method.

   @Override
               public Map<String, String> getHeaders() throws AuthFailureError {
                   Map<String, String> headers = new HashMap<String, String>();
                   headers.put("Authorization",”Client-Id {client-id});
                   return headers;
               }

Override the getHeader method of Volley library and return a map which has a key named “Authorization” and value is client id of Imgur.

Now we are ready to upload an image on Imgur through Phimpme Android app.

The problem I faced:

Whenever I was trying to upload large size images, I was getting volleytimeout exception, by default connection timeout was not sufficient to upload large files, so I resolved this error by adding below line in the request policy.

           request.setRetryPolicy(new DefaultRetryPolicy( 50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Now it works seamlessly with large files even on slow internet network and we are receiving the URL of the image in the response.

Resources :

Continue ReadingUpload Image to Imgur Anonymously Using Volley in Phimpme Android app