Wednesday, October 1, 2014

Capture and Cropping Image using device camera

This tutorial will help us to capture & cropping Image without using inbuilt  standard crop action intent

All of you know all  Android devices having inbuilt camera application. using this we can capture Image.

Step 1: This below code is useful to capture & display Image

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

public class MainActivity extends Activity {
Button button;
ImageView imageview=null;
final int CAMERA_CAPTURE = 1;
private Uri pic_uri;
 final int REQUEST_CODE_CROP_IMAGE=2
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
imageview=(ImageView)findViewById(R.id.textView1);

button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
   //we will handle the returned data in onActivityResult
   startActivityForResult(captureIntent, CAMERA_CAPTURE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
     {
      case CAMERA_CAPTURE:
    if (resultCode == RESULT_OK)
 {
    pic_uri = data.getData();
 .
           // this below code will use for display image without cropping.

          Bitmap bitmap = BitmapFactory.decodeFile(pic_uri.getPath());
    imageview.setImageBitmap(bitmap);
or 
            //  this below code will work with capture & cropping image
                Intent intent = new Intent(this, CropImage.class);
intent.putExtra(CropImage.IMAGE_PATH, getRealPathFromURI(pic_uri ));
intent.putExtra(CropImage.SCALE, true);
intent.putExtra(CropImage.ASPECT_X, 3);
intent.putExtra(CropImage.ASPECT_Y, 2);
startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);

   }
case REQUEST_CODE_CROP_IMAGE:
if(CropImage.mSaveUri!=null)
 {
 Uri path=CropImage.mSaveUri;
 bitmap = BitmapFactory.decodeFile(path.getPath());
 userimage.setImageBitmap(bitmap);

}
}

XML code : activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.cameracaropp.MainActivity$PlaceholderFragment" >

    <ImageView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

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

</RelativeLayout>

Step 2:  Below code is useful for cropping image without using inbuilt Cropping  functionality


public class CropImage extends Activity {

final int IMAGE_MAX_SIZE = 1024;

private static final String TAG = "CropImage";
public static final String IMAGE_PATH = "image-path";
public static final String SCALE = "scale";
public static final String ORIENTATION_IN_DEGREES = "orientation_in_degrees";
public static final String ASPECT_X = "aspectX";
public static final String ASPECT_Y = "aspectY";
public static final String OUTPUT_X = "outputX";
public static final String OUTPUT_Y = "outputY";
public static final String SCALE_UP_IF_NEEDED = "scaleUpIfNeeded";
public static final String CIRCLE_CROP = "circleCrop";
public static final String RETURN_DATA = "return-data";
public static final String RETURN_DATA_AS_BITMAP = "data";
public static final String ACTION_INLINE_DATA = "inline-data";

// These are various options can be specified in the intent.
private Bitmap.CompressFormat mOutputFormat = Bitmap.CompressFormat.JPEG;
public static Uri mSaveUri = null;
private boolean mDoFaceDetection = true;
private boolean mCircleCrop = false;
private final Handler mHandler = new Handler();

private int mAspectX;
private int mAspectY;
private int mOutputX;
private int mOutputY;
private boolean mScale;
private CropImageView mImageView;
private ContentResolver mContentResolver;
private Bitmap mBitmap;
private String mImagePath;

boolean mWaitingToPick; // Whether we are wait the user to pick a face.
boolean mSaving; // Whether the "save" button is already clicked.
HighlightView mCrop;

// These options specifiy the output image size and whether we should
// scale the output to fit it (or just crop it).
private boolean mScaleUp = true;
String sourceData;
private final BitmapManager.ThreadSet mDecodingThreads = new BitmapManager.ThreadSet();

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle icicle) {

super.onCreate(icicle);
mContentResolver = getContentResolver();

requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.cropimage);

mImageView = (CropImageView) findViewById(R.id.image);

showStorageToast(this);
Intent intent = getIntent();
Bundle extras = intent.getExtras();

sourceData=getIntent().getExtras().getString("navigation");

if (extras != null) {
if (extras.getString(CIRCLE_CROP) != null) {

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
mImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

mCircleCrop = true;
mAspectX = 1;
mAspectY = 1;
}

mImagePath = extras.getString(IMAGE_PATH);


mBitmap = getBitmap(mImagePath);

if (extras.containsKey(ASPECT_X)
&& extras.get(ASPECT_X) instanceof Integer) {

mAspectX = extras.getInt(ASPECT_X);
} else {

throw new IllegalArgumentException("aspect_x must be integer");
}
if (extras.containsKey(ASPECT_Y)
&& extras.get(ASPECT_Y) instanceof Integer) {

mAspectY = extras.getInt(ASPECT_Y);
} else {

throw new IllegalArgumentException("aspect_y must be integer");
}
mOutputX = extras.getInt(OUTPUT_X);
mOutputY = extras.getInt(OUTPUT_Y);
mScale = extras.getBoolean(SCALE, true);
mScaleUp = extras.getBoolean(SCALE_UP_IF_NEEDED, true);
}

if (mBitmap == null) {

Log.d(TAG, "finish!!!");
finish();
return;
}

// Make UI fullscreen.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

findViewById(R.id.discard).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {

setResult(RESULT_CANCELED);
finish();
}
});

findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

try {
mSaveUri = getImageUri(mImagePath);
onSaveClicked();
} catch (Exception e) {
finish();
}
}
});
findViewById(R.id.rotateLeft).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {

mBitmap = rotateImage(mBitmap, -90);
RotateBitmap rotateBitmap = new RotateBitmap(mBitmap);
mImageView.setImageRotateBitmapResetBase(rotateBitmap,
true);
mRunFaceDetection.run();
}
});

findViewById(R.id.rotateRight).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {

mBitmap = rotateImage(mBitmap, 90);
RotateBitmap rotateBitmap = new RotateBitmap(mBitmap);
mImageView.setImageRotateBitmapResetBase(rotateBitmap,
true);
mRunFaceDetection.run();
}
});
startFaceDetection();
}

public static Bitmap rotateImage(Bitmap src, float degree) {
// create new matrix
Matrix matrix = new Matrix();
// setup rotation degree
matrix.postRotate(degree);
Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(),
src.getHeight(), matrix, true);
return bmp;
}

private Uri getImageUri(String path) {

return Uri.fromFile(new File(path));
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
private Bitmap getBitmap(String path) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;

if (height > 1000) {
inSampleSize = Math.round((float) height / (float) 1000);
}
int expectedWidth = width / inSampleSize;

if (expectedWidth > 700) {
// if(Math.round((float)width / (float)reqWidth) > inSampleSize) //
// If bigger SampSize..
inSampleSize = Math.round((float) width / (float) 700);
}

options.inSampleSize = inSampleSize;

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;

return BitmapFactory.decodeFile(path, options);
}

private void startFaceDetection() {

if (isFinishing()) {
return;
}

mImageView.setImageBitmapResetBase(mBitmap, true);
mRunFaceDetection.run();
/*
* Util.startBackgroundJob(this, null, "Please wait\u2026", new
* Runnable() { public void run() {
*
* final CountDownLatch latch = new CountDownLatch(1); final Bitmap b =
* mBitmap; mHandler.post(new Runnable() { public void run() {
*
* if (b != mBitmap && b != null) {
* mImageView.setImageBitmapResetBase(b, true); mBitmap.recycle();
* mBitmap = b; } if (mImageView.getScale() == 1F) {
* mImageView.center(true, true); } latch.countDown(); } }); try {
* latch.await(); } catch (InterruptedException e) { throw new
* RuntimeException(e); }
*
*
* } }, mHandler);
*/
}

private void onSaveClicked() throws Exception {
// TODO this code needs to change to use the decode/crop/encode single
// step api so that we don't require that the whole (possibly large)
// bitmap doesn't have to be read into memory
if (mSaving)
return;
if (mCrop == null) {
return;
}

mSaving = true;

Rect r = mCrop.getCropRect();

int width = r.width();
int height = r.height();

// If we are circle cropping, we want alpha channel, which is the
// third param here.
Bitmap croppedImage;
try {

croppedImage = Bitmap.createBitmap(width, height,
mCircleCrop ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
} catch (Exception e) {
throw e;
}
if (croppedImage == null) {

return;
}

{
Canvas canvas = new Canvas(croppedImage);
Rect dstRect = new Rect(0, 0, width, height);
canvas.drawBitmap(mBitmap, r, dstRect, null);
}

if (mCircleCrop) {

// OK, so what's all this about?
// Bitmaps are inherently rectangular but we want to return
// something that's basically a circle. So we fill in the
// area around the circle with alpha. Note the all important
// PortDuff.Mode.CLEAR.
Canvas c = new Canvas(croppedImage);
Path p = new Path();
p.addCircle(width / 2F, height / 2F, width / 2F, Path.Direction.CW);
c.clipPath(p, Region.Op.DIFFERENCE);
c.drawColor(0x00000000, PorterDuff.Mode.CLEAR);
}
/* If the output is required to a specific size then scale or fill */
if (mOutputX != 0 && mOutputY != 0)
{

if (mScale) {

/* Scale the image to the required dimensions */
Bitmap old = croppedImage;
croppedImage = transform(new Matrix(), croppedImage, mOutputX,
mOutputY, mScaleUp);
if (old != croppedImage) {

old.recycle();
}
} else {

/*
* Don't scale the image crop it to the size requested. Create
* an new image with the cropped image in the center and the
* extra space filled.
*/

// Don't scale the image but instead fill it so it's the
// required dimension
Bitmap b = Bitmap.createBitmap(mOutputX, mOutputY,
Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(b);

Rect srcRect = mCrop.getCropRect();
Rect dstRect = new Rect(0, 0, mOutputX, mOutputY);

int dx = (srcRect.width() - dstRect.width()) / 2;
int dy = (srcRect.height() - dstRect.height()) / 2;

/* If the srcRect is too big, use the center part of it. */
srcRect.inset(Math.max(0, dx), Math.max(0, dy));

/* If the dstRect is too big, use the center part of it. */
dstRect.inset(Math.max(0, -dx), Math.max(0, -dy));

/* Draw the cropped bitmap in the center */
canvas.drawBitmap(mBitmap, srcRect, dstRect, null);

/* Set the cropped bitmap as the new bitmap */
croppedImage.recycle();
croppedImage = b;
}
}

// Return the cropped image directly or save it to the specified URI.
Bundle myExtras = getIntent().getExtras();
if (myExtras != null
&& (myExtras.getParcelable("data") != null || myExtras
.getBoolean(RETURN_DATA))) {

Bundle extras = new Bundle();
extras.putParcelable(RETURN_DATA_AS_BITMAP, croppedImage);
setResult(RESULT_OK, (new Intent()).setAction(ACTION_INLINE_DATA)
.putExtras(extras));
finish();
} else {
final Bitmap b = croppedImage;
saveOutput(b);
/*
* Util.startBackgroundJob(this, null,
* getString(R.string.saving_image), new Runnable() { public void
* run() {
*
*
* } }, mHandler);
*/
}

}

public static Bitmap transform(Matrix scaler, Bitmap source,
int targetWidth, int targetHeight, boolean scaleUp) {

int deltaX = source.getWidth() - targetWidth;
int deltaY = source.getHeight() - targetHeight;
if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
/*
* In this case the bitmap is smaller, at least in one dimension,
* than the target. Transform it by placing as much of the image as
* possible into the target and leaving the top/bottom or left/right
* (or both) black.
*/
Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b2);

int deltaXHalf = Math.max(0, deltaX / 2);
int deltaYHalf = Math.max(0, deltaY / 2);
Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf
+ Math.min(targetWidth, source.getWidth()), deltaYHalf
+ Math.min(targetHeight, source.getHeight()));
int dstX = (targetWidth - src.width()) / 2;
int dstY = (targetHeight - src.height()) / 2;
Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight
- dstY);
c.drawBitmap(source, src, dst, null);
return b2;
}
float bitmapWidthF = source.getWidth();
float bitmapHeightF = source.getHeight();

float bitmapAspect = bitmapWidthF / bitmapHeightF;
float viewAspect = (float) targetWidth / targetHeight;

if (bitmapAspect > viewAspect) {
float scale = targetHeight / bitmapHeightF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
} else {
float scale = targetWidth / bitmapWidthF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
}

Bitmap b1;
if (scaler != null) {
// this is used for minithumb and crop, so we want to mFilter here.
b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), scaler, true);
} else {
b1 = source;
}

int dx1 = Math.max(0, b1.getWidth() - targetWidth);
int dy1 = Math.max(0, b1.getHeight() - targetHeight);
Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth,
targetHeight);

if (b1 != source) {
b1.recycle();
}
return b2;
}

private void saveOutput(Bitmap croppedImage) {

if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
if (outputStream != null) {
croppedImage.compress(mOutputFormat, 90, outputStream);
}
} catch (IOException ex)
{
Log.e(TAG, "Cannot open file: " + mSaveUri, ex);
setResult(RESULT_CANCELED);
finish();
return;
} finally {

// Util.closeSilently(outputStream);
}
/*
* Intent intent = new
* Intent(CropImage.this,editmsuserprofile.class);
* intent.putExtra(IMAGE_PATH, mImagePath); startActivity(intent);
*/
} else {

Log.e(TAG, "not defined image url");
}
/*if(sourceData.equals("gallery"))
{
Intent i=new Intent(CropImage.this,editmsuserprofile.class);
i.putExtra("page navigation", "cropImage");
startActivity(i);
}*/
croppedImage.recycle();
finish();
}

public static int getOrientationInDegree(Activity activity) {

int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;

switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}

return degrees;
}

@Override
protected void onPause() {

super.onPause();
BitmapManager.instance().cancelThreadDecoding(mDecodingThreads);
}

@Override
protected void onDestroy() {

super.onDestroy();

if (mBitmap != null) {

mBitmap.recycle();
}
}

Runnable mRunFaceDetection = new Runnable() {
@SuppressWarnings("hiding")
float mScale = 1F;
Matrix mImageMatrix;
FaceDetector.Face[] mFaces = new FaceDetector.Face[3];
int mNumFaces;

// For each face, we create a HightlightView for it.
private void handleFace(FaceDetector.Face f) {

PointF midPoint = new PointF();

int r = ((int) (f.eyesDistance() * mScale)) * 2;
f.getMidPoint(midPoint);
midPoint.x *= mScale;
midPoint.y *= mScale;

int midX = (int) midPoint.x;
int midY = (int) midPoint.y;

HighlightView hv = new HighlightView(mImageView);

int width = mBitmap.getWidth();
int height = mBitmap.getHeight();

Rect imageRect = new Rect(0, 0, width, height);

RectF faceRect = new RectF(midX, midY, midX, midY);
faceRect.inset(-r, -r);
if (faceRect.left < 0) {
faceRect.inset(-faceRect.left, -faceRect.left);
}

if (faceRect.top < 0) {
faceRect.inset(-faceRect.top, -faceRect.top);
}

if (faceRect.right > imageRect.right) {
faceRect.inset(faceRect.right - imageRect.right, faceRect.right
- imageRect.right);
}

if (faceRect.bottom > imageRect.bottom) {
faceRect.inset(faceRect.bottom - imageRect.bottom,
faceRect.bottom - imageRect.bottom);
}

hv.setup(mImageMatrix, imageRect, faceRect, mCircleCrop,
mAspectX != 0 && mAspectY != 0);

mImageView.add(hv);
}

// Create a default HightlightView if we found no face in the picture.
private void makeDefault() {

HighlightView hv = new HighlightView(mImageView);

int width = mBitmap.getWidth();
int height = mBitmap.getHeight();

Rect imageRect = new Rect(0, 0, width, height);

// make the default size about 4/5 of the width or height
int cropWidth = Math.min(width, height) * 4 / 5;
int cropHeight = cropWidth;

if (mAspectX != 0 && mAspectY != 0) {

if (mAspectX > mAspectY) {

cropHeight = cropWidth * mAspectY / mAspectX;
} else {

cropWidth = cropHeight * mAspectX / mAspectY;
}
}

int x = (width - cropWidth) / 2;
int y = (height - cropHeight) / 2;

RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight);
hv.setup(mImageMatrix, imageRect, cropRect, mCircleCrop,
mAspectX != 0 && mAspectY != 0);

mImageView.mHighlightViews.clear(); // Thong added for rotate

mImageView.add(hv);
}

// Scale the image down for faster face detection.
private Bitmap prepareBitmap() {

if (mBitmap == null) {

return null;
}

// 256 pixels wide is enough.
if (mBitmap.getWidth() > 256) {

mScale = 256.0F / mBitmap.getWidth();
}
Matrix matrix = new Matrix();
matrix.setScale(mScale, mScale);
return Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
mBitmap.getHeight(), matrix, true);
}

public void run() {

mImageMatrix = mImageView.getImageMatrix();
Bitmap faceBitmap = prepareBitmap();

mScale = 1.0F / mScale;
if (faceBitmap != null && mDoFaceDetection) {
FaceDetector detector = new FaceDetector(faceBitmap.getWidth(),
faceBitmap.getHeight(), mFaces.length);
mNumFaces = detector.findFaces(faceBitmap, mFaces);
}

if (faceBitmap != null && faceBitmap != mBitmap) {
faceBitmap.recycle();
}

mHandler.post(new Runnable() {
public void run() {

mWaitingToPick = mNumFaces > 1;
if (mNumFaces > 0) {
for (int i = 0; i < mNumFaces; i++) {
handleFace(mFaces[i]);
}
} else {
makeDefault();
}
mImageView.invalidate();
if (mImageView.mHighlightViews.size() == 1) {
mCrop = mImageView.mHighlightViews.get(0);
mCrop.setFocus(true);
}

if (mNumFaces > 1) {
Toast.makeText(CropImage.this, "Multi face crop help",
Toast.LENGTH_SHORT).show();
}
}
});
}
};

public static final int NO_STORAGE_ERROR = -1;
public static final int CANNOT_STAT_ERROR = -2;

public static void showStorageToast(Activity activity) {

showStorageToast(activity, calculatePicturesRemaining(activity));
}

public static void showStorageToast(Activity activity, int remaining) {

String noStorageText = null;

if (remaining == NO_STORAGE_ERROR) {

String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_CHECKING)) {

noStorageText = activity.getString(R.string.preparing_card);
} else {

noStorageText = activity.getString(R.string.no_storage_card);
}
} else if (remaining < 1) {

noStorageText = activity.getString(R.string.not_enough_space);
}

if (noStorageText != null) {

Toast.makeText(activity, noStorageText, 5000).show();
}
}

public static int calculatePicturesRemaining(Activity activity) {

try {
/*
* if (!ImageManager.hasStorage()) { return NO_STORAGE_ERROR; } else
* {
*/
String storageDirectory = "";
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
storageDirectory = Environment.getExternalStorageDirectory()
.toString();
} else {
storageDirectory = activity.getFilesDir().toString();
}
StatFs stat = new StatFs(storageDirectory);
float remaining = ((float) stat.getAvailableBlocks() * (float) stat
.getBlockSize()) / 400000F;
return (int) remaining;
// }
} catch (Exception ex) {
// if we can't stat the filesystem then we don't know how many
// pictures are remaining. it might be zero but just leave it
// blank since we really don't know.
return CANNOT_STAT_ERROR;
}
}

}.

cropimage.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <view
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/relative"
        class="com.msapplication.msapp.crop.CropImageView"
        android:background="#000" />

    <RelativeLayout
        android:id="@+id/relative"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="#000"
        android:orientation="horizontal"
        android:paddingLeft="10dip"
        android:paddingRight="10dip" >

        <Button
            android:id="@+id/discard"
            style="CropButton"
            android:layout_width="80dp"
            android:layout_height="fill_parent"
            android:layout_marginLeft="20dp"
            android:text="@string/cancel"
            android:textColor="#000" />

        <ImageButton
            android:id="@+id/rotateLeft"
            android:layout_width="50dp"
            android:layout_height="fill_parent"
            android:layout_toRightOf="@id/discard"
            android:src="@drawable/ic_rotate_left" />

        <ImageButton
            android:id="@+id/rotateRight"
            android:layout_width="50dp"
            android:layout_height="fill_parent"
            android:layout_toRightOf="@id/rotateLeft"
            android:src="@drawable/ic_rotate_right" />

        <Button
            android:id="@+id/save"
            android:layout_width="80dp"
            android:layout_height="fill_parent"
            android:layout_toRightOf="@id/rotateRight"
            android:text="save"
            android:textColor="#000" />
    </RelativeLayout>

</RelativeLayout>

public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();

mString = cursor.getString(column_index);
decodeFile(mString);
return mString;

}

public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize=8;
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);

// The new size we want to scale to
final int REQUIRED_SIZE = 1024;

// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}

// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);

userimage.setImageBitmap(bitmap);
userimageGinger.setImageBitmap(picassabitmap);

}

1 comment: