接上一篇
package com.example.image;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageView;public class MainActivity extends Activity implements OnClickListener { private static final int TK_OK = 1; // 图库 private static final int XJ_OK = 2; // 相机 private static final int xj_OK_JQ = 3; // 相机拍照之后截取 private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView = (ImageView) findViewById(R.id.iv); findViewById(R.id.btn_xj).setOnClickListener(this); findViewById(R.id.btn_tk).setOnClickListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == TK_OK) { Bundle bundle = data.getExtras(); Bitmap tkPhoto = (Bitmap) bundle.get("data"); mImageView.setImageBitmap(tkPhoto); } else if (requestCode == XJ_OK) { final Bitmap xjPhoto = data.getParcelableExtra("data"); if (xjPhoto != null) { doCropPhoto(xjPhoto); } } else if (requestCode == xj_OK_JQ) { Bitmap xjJQPhoto = data.getParcelableExtra("data"); if (xjJQPhoto != null) { mImageView.setImageBitmap(xjJQPhoto); } } } } protected void doCropPhoto(Bitmap data) { Intent intent = getCropImageIntent(data); startActivityForResult(intent, xj_OK_JQ); } /** * 用于拍照之后返回的照片裁剪 * @param data * @return */ public static Intent getCropImageIntent(Bitmap data) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setType("image/*"); intent.putExtra("data", data); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 128); intent.putExtra("outputY", 128); intent.putExtra("return-data", true); return intent; } @Override public void onClick(View v) { if (v.findViewById(R.id.btn_xj) == v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, XJ_OK); } else if (v.findViewById(R.id.btn_tk) == v) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); //获取系统图库并裁剪 intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 300); intent.putExtra("outputY", 300); intent.putExtra("scale", true); intent.putExtra("return-data", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, TK_OK); } }}