Tuesday, August 6, 2013

How to pick the Image thumb-nail from gallery in android

We can pick the Image thumb-nail from gallery using Intent.



Note : at the end of  this Tutorial , you can find zip source code of this example .

There are two types of thumbnails available:
MINI_KIND: 512 x 384 thumbnail
MICRO_KIND: 96 x 96 thumbnail (Size is 18 or 36 kb depends on Devices)

1. We need to Create an Intent for pick Image from Gallery.
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

2. Override the method to get the result Image thumb-nail picked from Android Device.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Here is the place we got picked thumb-nail data
}

3. Get thumb-nail from Data result.

ContentResolver resolver = getContentResolver();
Uri actualUri = data.getData();
List uriPath = actualUri.getPathSegments();
long imageId = Long.parseLong(uriPath.get(uriPath.size() - 1));

Bitmap thumb = Thumbnails.getThumbnail(resolver, imageId,Thumbnails.MICRO_KIND, null);

4. Get thumb-nail Path.

private String getFilePath(Uri data){
        String path = "";
        path = data.getPath();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(data,filePathColumn, null, null, null);
        if(cursor!=null){
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            path = cursor.getString(columnIndex);
            cursor.close();
        }
        return path;
    }

4. Rotate Thumb-nail if it’s required.

String thumbPath = getFilePath(actualUri);
ExifInterface exif;
try 
{
exif = new ExifInterface(thumbPath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
/*
Note: resultBitmap (I have declared in Class)
[private Bitmap resultBitmap = null;]
*/
if(resultBitmap != null)
{
Log.d("", "Recycling:resultBitmap");
resultBitmap.recycle();
resultBitmap =null;
}
//Create bitmap thumb-nail with perfect orientation
resultBitmap = Bitmap.createBitmap(thumb, 0, 0, thumb.getWidth(),thumb.getHeight(), matrix, true);
} catch (Exception e) {
e.printStackTrace();
}

5. Set the Result Image Thumb-nail Bitmap on ImageView

imageView.setImageBitmap(resultBitmap);

Note: What if Image doesn’t have Thumbnail.
I have handled it in sample code, we will get the image and create thumbnail.

We will create very simple app to do this work
 -------------------------------------------
App Name: PickImageThumbnailFromGallery
Package Name: com.rdc. PickImageThumbnailFromGallery
Android SDK: Android SDK 2.2 / API 8
Default Activity Name: MainActivity.java

-------------------------------------------

MainActivity.java

package com.rdc.pickimagethumbnailfromgallery;

import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Thumbnails;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

 private ImageView imageView = null;
 private Button button = null;
 private Bitmap bitmap = null;

 private static final int PICK_IMAGE = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  imageView = (ImageView) findViewById(R.id.imageView1);
  button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(this);

 }

 @Override
 public void onClick(View arg0) {
  Intent i = new Intent(Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(i, PICK_IMAGE);
 }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  try {
   ContentResolver resolver = getContentResolver();
   Uri actualUri = data.getData();
   List uriPath = actualUri.getPathSegments();
   long imageId = Long.parseLong(uriPath.get(uriPath.size() - 1));
   Bitmap thumb = Thumbnails.getThumbnail(resolver, imageId,
   Thumbnails.MICRO_KIND, null);
   
   //There is no thumb-nail with this Image
   if (thumb == null) {
    // Log.d(TAG, "Failed to get thumb-nail for this image.");
    Toast.makeText(getApplicationContext(),
      "Failed to get thumbnail for our image.",
      Toast.LENGTH_SHORT).show();
    
    //so create thumb-nail from image itself
    Cursor cursor = resolver
      .query(actualUri,
        new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
        null, null, null);
    cursor.moveToFirst();
    final String imageFilePath = cursor.getString(0);
    cursor.close();

    imageView.setImageBitmap(this.createImageThumbnail(imageFilePath,
      100, 100));
   } 
   //We got the thumb-nail from gallery, rotate if needed else use on ImageView
   else {
    String thumbPath = getFilePath(actualUri);
    ExifInterface exif;
    try {
     exif = new ExifInterface(thumbPath);
     int orientation = exif.getAttributeInt(
       ExifInterface.TAG_ORIENTATION, 0);
     Matrix matrix = new Matrix();
     if (orientation == 6) {
      matrix.postRotate(90);
     } else if (orientation == 3) {
      matrix.postRotate(180);
     } else if (orientation == 8) {
      matrix.postRotate(270);
     }

     if (bitmap != null) {
      bitmap.recycle();
      bitmap = null;
     }

     bitmap = Bitmap.createBitmap(thumb, 0, 0, thumb.getWidth(),
       thumb.getHeight(), matrix, true);

     if (thumb != bitmap) {
      thumb.recycle();
      thumb = null;
     }
     imageView.setImageBitmap(bitmap);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 Bitmap createImageThumbnail(String imagePath, int width, int height) {
  BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
  bmpFactoryOptions.inJustDecodeBounds = true;
  int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
    / (float) height);
  int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
    / (float) width);

  if (heightRatio > 1 || widthRatio > 1) {
   if (heightRatio > widthRatio) {
    bmpFactoryOptions.inSampleSize = heightRatio;
   } else {
    bmpFactoryOptions.inSampleSize = widthRatio;
   }
  }
  bmpFactoryOptions.inJustDecodeBounds = false;

  if (bitmap != null) {
   bitmap.recycle();
   bitmap = null;
  }

  bitmap = BitmapFactory.decodeFile(imagePath, bmpFactoryOptions);
  return bitmap;
 }

 private String getFilePath(Uri data) {
  String path = "";
  path = data.getPath();
  String[] filePathColumn = { MediaStore.Images.Media.DATA };
  Cursor cursor = getContentResolver().query(data, filePathColumn, null,
    null, null);
  if (cursor != null) {
   cursor.moveToFirst();
   int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
   path = cursor.getString(columnIndex);
   cursor.close();
  }
  return path;
 }

}


activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="20dp"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PickImage" />

</LinearLayout>


ApplicatoinManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rdc.pickimagethumbnailfromgallery"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.rdc.pickimagethumbnailfromgallery.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



The output Screen will be like this..

Note: before click on upload image button make sure your Android Device is not connected with Computer.

Click to get thumbnail



You can download the complete source code zip file here : PickImageThumbnailFromGallery.Zip