先声明一点变量
private AlertDialog dialog; private static final int PHOTO_REQUEST_TAKEPHOTO = 1; private static final int PHOTO_REQUEST_GALLERY = 2; private static final int PHOTO_REQUEST_CUT = 3; File tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName()); private int crop = 180;
一个简单的点击事件不多说了
<span style="font-size:14px;">personDetailsHeadImg = (ImageButton) findViewById(R.id.person_details_head_img);//用于显示获取的图片</span>
<span style="font-size:14px;">personHeadRela = (RelativeLayout) findViewById(R.id.person_head_rela);//点击开始选择相册还是照相 personHeadRela.setOnClickListener(new onlistener());</span>
case R.id.person_head_rela: if (dialog == null) { dialog = new AlertDialog.Builder(PersonDetailsActivity.this).setItems(new String[] { "相机", "相册" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { if (which == 0) { //调用系统的照相机程序 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(tempFile)); startActivityForResult(intent,PHOTO_REQUEST_TAKEPHOTO); } else { //调用系统的相册 Intent intent = new Intent(Intent.ACTION_PICK,null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*"); startActivityForResult(intent,PHOTO_REQUEST_GALLERY); } } }).create(); } if (!dialog.isShowing()) { dialog.show(); } break;
protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub switch (requestCode) { case PHOTO_REQUEST_TAKEPHOTO: startPhotoZoom(Uri.fromFile(tempFile), 150); break; case PHOTO_REQUEST_GALLERY: if (data != null) startPhotoZoom(data.getData(), 150); break; case PHOTO_REQUEST_CUT: if (data != null) setPicToView(data); break; } super.onActivityResult(requestCode, resultCode, data); }</span>下面把图片进行处理裁切,给图片取个名字
<span style="font-size:14px;"> private void startPhotoZoom(Uri uri, int size) { Log.e("zoom", "begin"); Intent intent = new Intent("com.android.camera.action.CROP");//调用系统提供的裁切 intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1);// 裁剪框比例 intent.putExtra("aspectY", 1); intent.putExtra("outputX", crop);// 输出图片大小 intent.putExtra("outputY", crop); intent.putExtra("return-data", true); startActivityForResult(intent, PHOTO_REQUEST_CUT); } private void setPicToView(Intent picdata) { Bundle bundle = picdata.getExtras(); if (bundle != null) { Bitmap photo = bundle.getParcelable("data"); Drawable drawable = new BitmapDrawable(photo); personDetailsHeadImg.setBackgroundDrawable(drawable); } } private String getPhotoFileName() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat( "'IMG'_yyyyMMdd_HHmmss"); return dateFormat.format(date) + ".jpg"; }</span>
就这样大功告成!
免费源码地址:http://download.csdn.net/detail/tangpengtp/8249595
好了,各位留个言、点个赞算是对我的支持,多谢大家~