Saturday 4 April 2015

Dialog to pick a image From Camera Or Gallery


Mostly we require to get an image from camera or gallery in our apps ,So here how to go about it :-
Tested this code on 5.1 android lolipop works fine hope this helps all :-)

1. CameraActivity.java

public class CameraActivity extends Activity {
Uri outputFileUri;
String selectedImagePath = "";
ImageView mUserImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
initiViews();
}

private void initiViews() {

mUserImage = (ImageView) findViewById(R.id.mUserImage);

mUserImage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

popmenu();
}
});

}

void popmenu() {
final Dialog dialog = new Dialog(CameraActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.cameradialog);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button mCamerabtn = (Button) dialog.findViewById(R.id.cameradialogbtn);
Button mGallerybtn = (Button) dialog
.findViewById(R.id.gallerydialogbtn);
Button btnCancel = (Button) dialog.findViewById(R.id.canceldialogbtn);

dialog.getWindow().setLayout(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);

mCamerabtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"test.jpg");

outputFileUri = Uri.fromFile(file);
Log.d("TAG", "outputFileUri intent" + outputFileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);

dialog.cancel();
}
});

mGallerybtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
dialog.cancel();
}
});

btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel(); // dismissing the popup
}
});

dialog.show();

}

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

switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Log.d("TAG", "outputFileUri RESULT_OK" + outputFileUri);
if (outputFileUri != null) {

Bitmap bitmap;
bitmap = decodeSampledBitmapFromUri(outputFileUri,
mUserImage.getWidth(), mUserImage.getHeight());

if (bitmap == null) {
Toast.makeText(
getApplicationContext(),
"the image data could not be decoded"
+ outputFileUri.getPath(),
Toast.LENGTH_LONG).show();

} else {
selectedImagePath = getRealPathFromURI(CameraActivity.this,outputFileUri);// outputFileUri.getPath().
Toast.makeText(
getApplicationContext(),
"Decoded Bitmap: " + bitmap.getWidth() + " x "
+ bitmap.getHeight()
+ outputFileUri.getPath(),
Toast.LENGTH_LONG).show();
mUserImage.setImageBitmap(bitmap);
}
}
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri targetUri = data.getData();
Log.d("TAG", "datae" + targetUri);
Bitmap bitmap;
bitmap = decodeSampledBitmapFromUri(targetUri,
mUserImage.getWidth(), mUserImage.getHeight());

if (bitmap == null) {
Toast.makeText(
getApplicationContext(),
"the image data could not be decoded"
+ targetUri.getPath(), Toast.LENGTH_LONG)
.show();

} else {
selectedImagePath = getPath(targetUri);// targetUri.getPath();
Toast.makeText(
getApplicationContext(),
"Decoded Bitmap: " + bitmap.getWidth() + " x "
+ bitmap.getHeight() + targetUri.getPath(),
Toast.LENGTH_LONG).show();
mUserImage.setImageBitmap(bitmap);
}
}
break;

default:
break;
}
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

public String getRealPathFromURI(Context context, Uri contentUri) {
   Cursor cursor = null;
   try {

       if("content".equals(contentUri.getScheme())) {
           String[] proj = {MediaStore.Images.Media.DATA};
           cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
       }
       else{
           return contentUri.getPath();
       }


   } finally {
       if (cursor != null) {
           cursor.close();
       }
   }
}  

public Bitmap decodeSampledBitmapFromUri(Uri uri, int reqWidth,
int reqHeight) {

Bitmap bm = null;

try {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri), null, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}

return bm;
}

public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
}



2. camera.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/mUserImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


3. cameradialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:background="@drawable/roundshape"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@null"
        android:padding="10dp"
        android:text="Blog Box"
        android:textSize="20sp"
        android:textStyle="bold" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="4dp"
        android:layout_marginLeft="4dp"
        android:background="#000000"
        android:layout_marginRight="4dp" />

    <Button
        android:id="@+id/cameradialogbtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        android:layout_weight=".3"
        android:background="@null"
        android:padding="5dp"
        android:text="Take a picture from camera"
        android:textSize="18sp" >
    </Button>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="4dp"
        android:background="#000000"
        android:layout_marginRight="4dp"
         />

    <Button
        android:id="@+id/gallerydialogbtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        android:layout_weight=".3"
        android:background="@null"
        android:padding="5dp"
        android:text="Choose from gallery"
        android:textSize="18sp" >
    </Button>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#000000"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp" />

    <Button
        android:id="@+id/canceldialogbtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="4dp"
        android:layout_weight=".3"
        android:background="@null"
        android:padding="5dp"
        android:text="No thanks"
        android:textSize="18sp" >
    </Button>

</LinearLayout>


4. Drawable : roundshape.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <stroke
        android:width="2dp"
        android:color="#FFFFFF" />

    <corners android:radius="10dp" />

    <gradient
        android:angle="270"
        android:centerColor="#FFFFFF"
        android:endColor="#f9d7f2"
        android:startColor="#f9d7f2" />

</shape>


Output : 








1 comment: