拍照后裁剪

private void doTakePhotoAction() {
    
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    //Wysie_Soh: Create path for temp file
    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

    try {
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PICK_FROM_CAMERA);
    } catch (ActivityNotFoundException e) {
        //Do nothing for now
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }

    switch (requestCode) {

    case CROP_FROM_CAMERA: {
        //Wysie_Soh: After a picture is taken, it will go to PICK_FROM_CAMERA, which will then come here
        //after the image is cropped.

        final Bundle extras = data.getExtras();

        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            mPhoto = photo;
            mPhotoChanged = true;
            mPhotoImageView.setImageBitmap(photo);
            setPhotoPresent(true);
        }

        //Wysie_Soh: Delete the temporary file                        
        File f = new File(mImageCaptureUri.getPath());            
        if (f.exists()) {
            f.delete();
        }

        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(mPhotoImageView, InputMethodManager.SHOW_IMPLICIT);

        break;
    }

    case PICK_FROM_CAMERA: {
        //Wysie_Soh: After an image is taken and saved to the location of mImageCaptureUri, come here
        //and load the crop editor, with the necessary parameters (96x96, 1:1 ratio)

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setClassName("com.android.camera", "com.android.camera.CropImage");

        intent.setData(mImageCaptureUri);
        intent.putExtra("outputX", 96);
        intent.putExtra("outputY", 96);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);            
        startActivityForResult(intent, CROP_FROM_CAMERA);

        break;

    }
    }
}

 具体可以参考

http://www.androidworks.com/crop_large_photos_with_android

Intent Details:

First, lets discuss this Intent, and its features.    After seeing some example code, I found that I could call it easily using an Intent like this:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType(“image/*”);
intent.putExtra(“crop”, “true”);

However, this is when I lacked additional documentation, what are the options, etc…  So, I have put together a table, and a demo program, in an attempt to demonstrated all available options from this control.  You may use my example code in your application, and expand upon it.  I’ll attach it to this post.

Exta Options Table for image/* crop:

 

SetExtraDataTypeDescription
cropStringSignals the crop feature
aspectXintAspect Ratio
aspectYintAspect Ratio
outputXintwidth of output created from this Intent
outputYintwidth of output created from this Intent
scalebooleanshould it scale
return-databooleanReturn the bitmap with Action=inline-data by using the data
dataParcelableBitmap to process, you may provide it a bitmap (not tested)
circleCropStringif this string is not null, it will provide some circular cr
MediaStore.EXTRA_OUTPUT ("output")URISet this URi to a File:///, see example code

Now, the biggest confusion is going to be around this MediaStore.EXTRA_OUTPUT and return-data options.

You basically have 2 ways to get the bitmap back from this Intent, you can ask for it inline or provide a Uri that it can write to.

Option #1:  If you set return-data to "true", you will get back an Action = inline-data, and the bitmap returned will be inside the (Bitmap)extras.getParcelable("data").  Note:  If the image ends up being to large, you will get a nasty exception with this method, so you are restricted to keeping your outputX and outputY small.  In my code example attached, I did NOT use that method because of this reason.

Here is the code from CropImage.java (Android source code) where they write it inline:


// 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("data", croppedImage);
setResult(RESULT_OK,(new Intent()).setAction("inline-data").putExtras(extras));
finish();

Option #2:  If you set return-data to "false", you will not receive a Bitmap back from the onActivityResult Intent in-line, instead you will need to set MediaStore.EXTRA_OUTPUT to a Uri (of File scheme only) where you want the Bitmap to be stored.  This has some restrictions, first you need to have a temp filesystem location in order to give the file scheme URI, not a huge problem (except on some devices that don't have sdcards).

Here is the code from CropImage.java (Android source code) where they write it to your Uri:


if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
if (outputStream != null) {
croppedImage.compress(mOutputFormat, 75, outputStream);
}
} catch (IOException ex) {
// TODO: report error to caller
Log.e(TAG, "Cannot open file: " + mSaveUri, ex);
} finally {
Util.closeSilently(outputStream);
}
Bundle extras = new Bundle();
setResult(RESULT_OK, new Intent(mSaveUri.toString())
.putExtras(extras));
}

Example Code

I have attached some example code that should allow you to test various configurations.  Let me know if you find it useful (or not).D
Download here -> MediaStoreTest

From the code (the essential parts)


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thiz = this;
setContentView(R.layout.main);
mBtn = (Button) findViewById(R.id.btnLaunch);
photo = (ImageView) findViewById(R.id.imgPhoto);

 

mBtn.setOnClickListener(new OnClickListener(){

public void onClick(View v) {
try {
// Launch picker to choose photo for selected contact
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("scale", scale);
intent.putExtra("return-data", return_data);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection",!faceDetection); // lol, negative boolean noFaceDetection
if (circleCrop) {
intent.putExtra("circleCrop", true);
}

startActivityForResult(intent, PHOTO_PICKED);
} catch (ActivityNotFoundException e) {
Toast.makeText(thiz, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
}
}
});

}

private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}

private File getTempFile() {
if (isSDCARDMounted()) {

File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(thiz, R.string.fileIOIssue, Toast.LENGTH_LONG).show();
}
return f;
} else {
return null;
}
}

private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();

if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}

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

switch (requestCode) {
case PHOTO_PICKED:
if (resultCode == RESULT_OK) {
if (data == null) {
Log.w(TAG, "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, R.string.no_photo_picked,
Toast.LENGTH_SHORT);
t.show();
return;
}

final Bundle extras = data.getExtras();
if (extras != null) {
File tempFile = getTempFile();
// new logic to get the photo from a URI
if (data.getAction() != null) {
processPhotoUpdate(tempFile);
}
}
}
break;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值