Adding Zooming Functionality For Gallery Images

Phimpme is an Android app which contains the camera, editing, sharing on different platforms and displaying local images. To display local images with swipe feature we also allow the user to zoom images with pinch and double tap action on an image. So in this post, I will be explaining how I added zooming functionality for images in phimpme.

To zoom an image we are using Photoview that is similar to an imageview means it support all option that imageview supports.

Step 1

The first step is to add the following dependency in your Gradle.build file of your project.

dependencies {
   compile 'com.github.chrisbanes:PhotoView:latest.release.here'
}

Step 2

Now replace your imageview with PhotoView and it can be done by following way.

<com.github.chrisbanes.photoview.PhotoView
   android:id="@+id/photo_view"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Now we can use this photoview as imageview and it will enable zoom functionality easily.

Step 3

Now next step is to load image in PhotoView. As phimpme allow to display local images of a device so we are using glide library to load image in PhotoView. We are using URI to load image in Glide.

PhotoView imageView = new PhotoView(ActivitySwitchHelper.context);


Glide.with(getContext())
       .load(media.get(position).getUri())
       .diskCacheStrategy(DiskCacheStrategy.SOURCE)
       .thumbnail(0.5f)
       .into(imageView);

Now your image view which is actually a PhotoView is ready to provide zoom functionality by double tap on and image and by pan-zoom.

PhotoView in Phimpme Android

Resources

Continue ReadingAdding Zooming Functionality For Gallery Images

Using RecyclerView Instead Of ViewPager For Gallery

Phimpme is an Image app that provide camera, editing ,sharing options and a gallery section. The Gallery section allows us to view large number of images that are locally available in the users device. Generally developers used viewpager to swipe the horizontal images although we are also using viewPager but the problem is it is taking more time to load large size images and that disturb the user smooth experience. After so much research I came to new solution. So in this post, I will be explaining how to use recyclerview to view gallery images instead of viewPager.

Let’s get started

Make sure you have Recyclerview support in your dependencies in build.gradle. As recyclerView required an adapter and viewHolder to set data in recyclerView. So I will be explaining about adapter.

ViewHolder for RecyclerView

public static class ViewHolder extends RecyclerView.ViewHolder {
  ImageView imageView;
  LinearLayout linearLayout;

  public ViewHolder(View itemView) {
      super(itemView);
      imageView = new ImageView(context);
      linearLayout = (LinearLayout) itemView.findViewById(R.id.layout);
      WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
      Display display = wm.getDefaultDisplay();
      Point size = new Point();
      display.getSize(size);
      int width = size.x;
      int height = size.y;
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
              width, height);
      imageView.setLayoutParams(params);
      imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
      linearLayout.addView(imageView);
  }
}

Right now the imageView is adjusting according to device screen size so that it will be compatible with all devices.

I am passing the width and height in LayoutParams to parent of imageview i.e in our case linearlayout is parentView.

Adapter for RecyclerView

public ImageAdapter(ArrayList<Media> media) {
  this.media = media;
}

@Override
public ImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.unit_image_pager, null, false);

  return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
  Glide.with(getContext())
          .load(media.get(position).getUri())
          .diskCacheStrategy(DiskCacheStrategy.SOURCE)
          .thumbnail(0.5f)
          .into(holder.imageView);
  holder.imageView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          basicCallBack.callBack(0,null);
      }
  });
}

MediaList is an arrray of media that contains the list of images with URI that will help to load images. I am using Glide to load images you can use any library to load images. Adapter helps to load data in recyclerView.

Now set viewPager where you require to scroll images horizontally

@Nullable @BindView(R.id.photos_pager)
RecyclerView mRecylerPager;
mRecylerPager.setLayoutManager(linearLayoutManager);
mRecylerPager.setHasFixedSize(true);
mRecylerPager.setLongClickable(true);

Our recycler view is ready now the most important part is to set things onPageChangeListner. For example : In Phimpme we are getting path of current position image to show in image description so to update the value we are writing that codde in onPageChangeListner and to update the toolbar.

mViewPager.setOnPageChangeListener(new PagerRecyclerView.OnPageChangeListener() {
  @Override
  public void onPageChanged(int oldPosition, int position) {
      getAlbum().setCurrentPhotoIndex(position);
      toolbar.setTitle((position + 1) + " " + getString(R.string.of) + " " + size_all);
      invalidateOptionsMenu();
      pathForDescription = getAlbum().getMedia().get(position).getPath();
  }
});

To scroll to the given position we require to set the position to recyclerView and it can be done by the following code

mViewPager.scrollToPosition(getCurrentPsotion());

This is how I implemented the recyclerView instead of ViewPager to load gallery images faster as compare to ViewPager.

RecyclerView in Phimpme to load gallery Images

Resources:     

 

Continue ReadingUsing RecyclerView Instead Of ViewPager For Gallery

Adding EditText With Google Input Option While Sharing In Phimpme App

In Phimpme Android App an user can share images on multiple platforms. While sharing we have also included caption option to enter description about the image. That caption can be entered by using keyboard as well Google Voice Input method. So in this post, I will be explaining how to add edittext with google voice input option.

Let’s get started

Step-1 Add EditText and Mic Button in layout file

<ImageView
       android:layout_width="20dp"
       android:id="@+id/button_mic"
       android:layout_height="20dp"
       android:background="?android:attr/selectableItemBackground"
       android:background="@drawable/ic_mic_black"
       android:scaleType="fitCenter" />
</RelativeLayout>


Caption Option in Share Activity in Phimpme

In Phimpme we have material design dialog box so right now I am using getTextInputDialogBox(). It will prompt the material design dialog box to enter caption to share image on multiple platform.

Step-2

Now we can get caption from edittext easily using the following code.

if (!captionText.isEmpty()) {
  caption = captionText;
  text_caption.setText(caption);
  captionEditText.setSelection(caption.length());
} else {
  caption = null;
  text_caption.setText(caption);
}


Step – 3 (Now add option Google Voice input option)

To use google input option I have added a global function in Utils class. To use that method just call that method with proper arguments.

public static void promptSpeechInput(Activity activity, int requestCode, View parentView, String promtMsg) {
  Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
  intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
  intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
  intent.putExtra(RecognizerIntent.EXTRA_PROMPT, promtMsg);
  try {
      activity.startActivityForResult(intent, requestCode);
  } catch (ActivityNotFoundException a) {
      SnackBarHandler.show(parentView,activity.getString(R.string.speech_not_supported));
  }

}

Just pass the request code to receive the speech text in onActvityResult() method and passs promt message which will be visible to user.

Step – 4 (Set text to caption )

if (requestCode == REQ_CODE_SPEECH_INPUT && data!=null){
       ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
       String voiceInput = result.get(0);
       text_caption.setText(voiceInput);
       caption = voiceInput;
       return;

}

Now we can set the text in caption string right now I am adding text in existing caption i.e If the user enter some text using edittext and after that user clicked on mic button then the extra text will be added after the previous text.

So this is how I have used Google voice input method and made the function globally.

Resources:

Continue ReadingAdding EditText With Google Input Option While Sharing In Phimpme App

Handle Large Size Images in Phimpme

Phimpme is an image app which provides custom camera, sharing features along with a well-featured gallery section. In gallery, it allows users to view local images. Right now we are using Glide to load images in the gallery, it is working fine for small size images it lags a bit when it comes to handling the high quality large images in the app. So in this post, I will explaining how to handle large size  images without lagging or without taking much time. To solve this problem I am using android universal image loader library which is very light when compared to glide.

Step – 1

First step is to include the dependency in the phimpme project and it can be done by the following way

dependencies {
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'
}

Step-2

After this create an Android universal image loader instance. We can create imageloader instance in our application class if we want to use the image loader globally.

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
       this).memoryCacheExtraOptions(480, 800).defaultDisplayImageOptions(defaultOptions)
       .diskCacheExtraOptions(480, 800, null).threadPoolSize(3)
       .threadPriority(Thread.NORM_PRIORITY - 2)
       .tasksProcessingOrder(QueueProcessingType.FIFO)
       .denyCacheImageMultipleSizesInMemory()
       .memoryCache(new LruMemoryCache(MAXMEMONRY / 5))
       .diskCache(new UnlimitedDiskCache(cacheDir))
       .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
       .imageDownloader(new BaseImageDownloader(this)) // default
       .imageDecoder(new BaseImageDecoder(false)) // default
       .defaultDisplayImageOptions(DisplayImageOptions.createSimple()).build();
 
 this.imageLoader = ImageLoader.getInstance();
 imageLoader.init(config);

Add the above code in the application class.


Step-3

Now our image loader instance is created now we can load an image easily. But to avoid the out of memory error and large image size error we can set many options to an image loader. In options we can set maximum memory allowed to image loader, maximum resolution and set particular architecture, it can be done in following ways.


Step-4

File cacheDir = com.nostra13.universalimageloader.utils.StorageUtils.getCacheDirectory(this);
 int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory());

To load an image using universal image loader just pass the URI of an image and to load write the below code.
Now the time is to load an image from local storage. We can load images from local storage, drawable, assets easily.

ImageLoader imageLoader = ((MyApplication)getApplicationContext()).getImageLoader();
 imageLoader.displayImage(imageUri, imageView);

This is how I handled large size image in Phimpme.

Large Image in Phimpme


References :

Continue ReadingHandle Large Size Images in Phimpme

How to Make Phimpme Android App Crash Free

Now Phimpme Android app is almost ready with lots of social sharing options. A user can upload images on multiple platforms like Tumblr, Flickr, Imgur, OwnCloud (open source), Nextcloud, dropbox, pinterest, etc. Apart from Sharing, Phimpme app also allow user to click image from own custom camera with different filters and various editing options. As everything is now almost ready so It also important to make app stable and crash free. To make app stable to compatible with all types of device, we can write instrumentation test cases. So in this post I will be explaining how I made Phimpme android app crash free. To do so I have integrated crash reporting service in Phimpme using Firebase Crash report service and Crashlytics.

Using Firebase Crash Reporting service:

Firebase is free of cost and provide various features along with crash reporting. To integrate firebase crash service there is step by step guide.

Step 1:

First, step is to register your app on firebase developer console. To register your Android app on firebase click here.  Add your app name and select your country.

 

Step 2:

Next, click on the Add Firebase to your Android app button and fill in the your Android application’s package name and the SHA-1 key. You can generate this key very easily with the help of Android studio. Type this command in your terminal to generate SHA-1

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

On successful completion of the command, the SHA-1 key will be displayed on the terminal.

Step 3:

Now add the SHA-1 and package name in firebase console. After that download googleservice.json file and place in app folder of your project.

Step 4:

Add following dependency in your android project and plugin in build.gradle

dependencies {
    classpath 'com.google.gms:google-services:3.1.0'
  }
 apply plugin: 'com.google.gms.google-services'


Step 5:

Once you have done the above four steps your app will be visible in firebase console and now you can add crash service. Now you can see crash in your firebase console

After this add the following dependency in build.gradle. This is very important.

compile 'com.google.firebase:firebase-crash:9.4.0'

Resources:

Continue ReadingHow to Make Phimpme Android App Crash Free

Adding Tumblr Upload Feature in Phimpme

The Phimpme Android application along with various other cloud storage and social media upload features provides an option to upload the images on Tumblr without having to download any other applications. In this post, I will be explaining how I integrated Tumblr in phimpme as there is no proper guide on the web how to integrate to Tumblr in Android. Tumblr provides an Android-SDK but there is no proper documentation to it and is not enough to authenticate and upload the images to it. After so much research I came to a solution. So read this article to know how to integrate Tumblr in Android.

Step 1:

First, add two dependencies to your project one is for Android SDK of Tumblr and one is for loglr which help you to get login on Tumblr.

dependencies {

compile 'com.daksh:loglr:1.2.1'

compile 'com.tumblr:jumblr:0.0.11'

}

Step 2:

  1. Register your app on Tumblr to obtain developer keys.
  2. Enter callback URL it is important to get keys.
  3. Generate CONSUMER_KEY & CONSUMER_SECRET from the official developer console of Tumblr.

Register your application

Step 3:

Now we use Loglr library to log in to Tumblr. Tumblr doesn’t provide any library to login so I am using Loglr library for login Tumblr. After successfully log in Loglr will return API_KEY and API_SECRET. We will use these keys later to upload the image. Save these keys as constant variables.

public final static String TUMBLR_CONSUMER_KEY = "ENTER-CONSUMER-KEY";

public final static String TUMBLR_CONSUMER_SECRET = "ENTER-CONSUMER-SECRET";

Step 4:

To authenticate the Tumblr use loglr login instance and it can be done as follows.

Loglr.getInstance()

     .setConsumerKey(Constants.TUMBLR_CONSUMER_KEY)

     .setConsumerSecretKey(Constants.TUMBLR_CONSUMER_SECRET)

     .setLoginListener(loginListener)

     .setExceptionHandler(exceptionHandler)

     .enable2FA(true)

     .setUrlCallBack(Constants.CALL_BACK_TUMBLR)

     .initiateInActivity(AccountActivity.this);

After that you will be prompt to enter your tumblr credentials to authenticate the phimpme Android app. Once you have done it will return api_token and api_secret. Now save this in database.

account.setToken(loginResult.getOAuthToken());

account.setSecret(loginResult.getOAuthTokenSecret());

Step 5:

Once the authentication is done now we can upload an image directly to Tumblr from the Share activity in the Phimpme Android application. To upload an image create an async task so that uploading process will run in a background thread and not block the main UI thread. Keep in mind Tumblr require 4 variable to create Tumblr client CONSUMER_KEY, CONSUMER_SECRET, API_KEY and API_SECRET. Now we can create a Tumblr client using these 4 values. Once the client is created we are ready to get data from Tumblr and upload an image on Tumblr. Before uploading an image on Tumblr we need blog name because the user can have multiple blogs on Tumblr so we need to ask the user to choose a blog name from the list or we can provide dialog to enter blog name manually. Now enter the following code in the doInBackground() method of asynctask.

PhotoPost post = null;

try {

 post = client.newPost(user.getBlogs().get(0).getName(), PhotoPost.class);

 if (caption!=null && !caption.isEmpty())

 post.setCaption(caption);

 post.setData(new File(imagePath));

 post.save();

} catch (IllegalAccessException | InstantiationException e) {

 success = false;

}

If success variable is true that means our image is uploaded successfully. This is how I implemented the upload feature to Tumblr using two different libraries. To get the full source code, please refer to the Phimpme Android repository.

Resources:

Continue ReadingAdding Tumblr Upload Feature in Phimpme

Drawing Lines on Images in Phimpme

In the editing section of the Phimpme app, we want a feature which lets the user write something on the image in their own handwriting. The user can also select different colour palette available inside the app. We aligned this feature in our editor section as Phimpme Image app allows a user to use our custom camera with the large number of editing options (Enhancement, Transform, Applying Stickers, Applying filters and writing on images). In this post, I am explaining how I implemented the draw feature in Phimpme Android app.

Let’s get started

Step -1: Create bitmap of Image and canvas to draw

The first step is to create a bitmap of Image on which you want to draw lines. Now we need a canvas to draw and canvas requires bitmap to work. So in this step, we will create a bitmap and new canvas to draw the line.

BitmapFactory.Options bmOptions = new BitmapFactory.Options();

Bitmap bitmap =  BitmapFactory.decodeFile(ImagePath, bmOptions);

Canvas canvas = new Canvas(bitmap);

Once the canvas is initialized, we use paint class to draw on the canvas.

Step-2: Create Paint class to draw on canvas

In this step, we will create a new Paint class with some properties like colour, Stroke Width and Coordinate where we want to draw a line and it can be done by using the following code.

Paint paint = new Paint();

paint.setColor(Color.rgb(255, 153, 51));

paint.setStrokeWidth(10);

int startx = 50;

int starty = 90;

int endx = 150;

int endy = 360;

canvas.drawLine(startx, starty, , endy, paint);

The above code will result in a straight line on the canvas like the below screenshot.

Step-3: Add support to draw on touch dynamically

In step 2 we have added the feature to draw a straight line, but what if the user wants to draw the lines on canvas with on touch event. So to achieve this we have to apply onTouchListener and applying coordinates dynamically and it can be done by using the following code.

@Override

public boolean onTouchEvent(MotionEvent event) {

 boolean ret = super.onTouchEvent(event);

 float x = event.getX();

 float y = event.getY();

 switch (event.getAction()) {

     case MotionEvent.ACTION_DOWN:

         ret = true;

         last_x = x;

         last_y = y;

         break;

     case MotionEvent.ACTION_MOVE:

         ret = true;

         canvas.drawLine(last_x, last_y, x, y);

         last_x = x;

         last_y = y;

         this.postInvalidate();

         break;

     case MotionEvent.ACTION_CANCEL:

     case MotionEvent.ACTION_UP:

         ret = false;

         break;

 }

 return ret;

}

Now the above code will let you draw the lines dynamically. But, how? The answer is In on touch event, I am fetching coordinates of touch and applying it dynamically to a canvas. Now our feature is ready to draw the lines on canvas with finger touch.

Drawing line in Phimpme Editor

Step – 4: Adding eraser functionality

Till now we have added the draw on canvas functionality, but what if the user wants to erase particular area. So now we have to implement the eraser functionality. It is very simple now what we have to do again we have to draw, but we will set paint color to the transparent color. It will draw the transparent color on the existing line which results in the previous picture and it looks like we are erasing. It can be done by adding one line.

paint.setColor(eraser ? Color.TRANSPARENT : color);

Now we have done by drawing the lines on an image and erasing functionality.

Resources:

Continue ReadingDrawing Lines on Images in Phimpme

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

Adding Text on an Image in Phimpme Android

As Phimpme Android is an image app which provides own custom camera, editing, and sharing images on multiple platforms, so we decided to introduce a new feature, where the user can write text on images.

Using this feature, a user can write text on images and share on multiple  platforms like Facebook, twitter, wordPress, drupal, pinterest, etc. In this post, I am going to explain how I implemented this feature.

Writing Text on image in Phimpme Android

How I implemented Text on Image in Phimpme

First, create an imageview and apply the original image bitmap or load with any image library by providing the local path of the image.

imageView.setImageBackgroundResources(imagePath);

Once an image is loaded we will ask a user to enter text in editext and the text will be displayed above the image. The code for this is:

EditText inputBox = (EditText) layout.findViewById(R.id.editText);
String textString = inputBox.getText().toString();

Now we have textString variable that stores the text we wanted to display. To set this text we need to create a textview on the image, which can be done as follows:

TextView textView = new TextView(context);
textView.setText(textString);

We allow the user to drag the text over image to his/her desired location. This is done using setOnTouchListener() as follows

TextView.setOnTouchListener(new View.OnTouchListener() {
    float lastX = 0, lastY = 0;
 
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case (MotionEvent.ACTION_DOWN):
                lastX = event.getX();
                lastY = event.getY();
 
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = event.getX() - lastX;
                float dy = event.getY() - lastY;
                float finalX = v.getX() + dx;
                float finalY = v.getY() + dy + v.getHeight();               v.setX(finalX;              
              v.setY(finalY);
              break;
              }
              return true;
              }
        });

Thus, we have set the text according to the user’s desired location.

Problem I faced

The text doesn’t appear to move from the desired position, instead, the text moves from some offset value. To solve this I have used two variable finalX and finaly. Now I am calculating the distance from the point to corner and adding the extra offset value to finalX and finalY. So this is how I achieve perfect image on text feature with point accuracy in Phimpme-Android.

Resources:

 

Continue ReadingAdding Text on an Image in Phimpme Android