Showing posts with label Gallery Image. Show all posts
Showing posts with label Gallery Image. Show all posts

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

Sunday, August 12, 2012

How to Pick Image from Gallery in Android



Today I just learn and going to share with you,
how we can get an image From Gallery in our Android app
so below is the step by step description also at last
you can find zip source code of this example.

We will create very simple app to do this work
 -------------------------------------------
App Name: PickGalleryImage
Package Name: com.rdc.activity
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: PickGalleryImageActivity.java
-------------------------------------------

PickGalleryImageActivity.java

package com.rdc.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class PickGalleryImageActivity extends Activity implements
		OnClickListener {

	private static int RESULT_LOAD_IMAGE = 1;
	private Button btnLoadImage = null;
	private ImageView imageView = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		btnLoadImage = (Button) findViewById(R.id.button_LoadPicture);
		btnLoadImage.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore
                              .Images.Media.EXTERNAL_CONTENT_URI);

		startActivityForResult(i, RESULT_LOAD_IMAGE);

	}
	
	
	@Override
    protected void onActivityResult(int requestCode, 
                                     int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if (requestCode == RESULT_LOAD_IMAGE && 
                              resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			
			imageView = (ImageView) findViewById(R.id.imageView);
			imageView.setImageBitmap(BitmapFactory
                            .decodeFile(picturePath));
		
		}
    
    
    }
	
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<ImageView
		android:layout_width="fill_parent"
		android:layout_weight="1"
		android:layout_height="wrap_content"
		android:id="@+id/imageView"></ImageView>
	<Button
		android:layout_height="wrap_content"
		android:text="Load Picture"
		android:layout_width="wrap_content"
		android:layout_weight="0"
		android:layout_gravity="center"
		android:id="@+id/button_LoadPicture"></Button>
</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc.activity"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".PickGalleryImageActivity"
			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 upload image


Just select any one image and see you got it here


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