安卓開發:使用系統的圖片選擇和剪切功能

很多項目中都會使用到選擇圖片、對圖片進行剪切的功能。系統為我們提供了一整套的處理接口,可以不用再自己寫這些繁瑣的代碼了。


//打開相冊

private voidopeanPhotoalbum() {

Intentintent1=newIntent(Intent.ACTION_PICK, null);

intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");

startActivityForResult(intent1,1);

}

//打開相機

private voidopeanCamera() {

Intentintent2=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);

intent2.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(newFile(Environment.getExternalStorageDirectory(),

"head.jpg")));

startActivityForResult(intent2,2);//采用ForResult打開

}

//在返回接口中處理

protected voidonActivityResult(intrequestCode, intresultCode,Intent data) {

switch(requestCode) {

case1:

if(resultCode ==RESULT_OK) {

cropPhoto(data.getData());//裁剪圖片

}

break;

case2:

if(resultCode ==RESULT_OK) {

Filetemp=newFile(Environment.getExternalStorageDirectory()

+"/head.jpg");

cropPhoto(Uri.fromFile(temp));

}//裁剪圖片

break;

case3:

if(data !=null) {

Bundleextras= data.getExtras();

head=extras.getParcelable("data");

if(head!=null) {

/**

* 上傳服務器代碼

*/

HeadImageViewUtils.setPicToView(head,path);

sendImage(head,actionUrl);

head= HeadImageViewUtils.compressImage(head,100);

mCircleImageView.setImageBitmap(head);

}else{

//mRequest.personalDataRequests(uid, this);

}

}

break;

}

}

/**

* 調用系統的裁剪

*

*@paramuri

*/

public voidcropPhoto(Uri uri) {

Intentintent=newIntent("com.android.camera.action.CROP");

intent.setDataAndType(uri,"image/*");

intent.putExtra("crop","true");

// aspectX aspectY 是寬高的比例

intent.putExtra("aspectX",1);

intent.putExtra("aspectY",1);

// outputX outputY 是裁剪圖片寬高

intent.putExtra("outputX",150);

intent.putExtra("outputY",150);

intent.putExtra("return-data", true);

startActivityForResult(intent,3);

}



startActivityForResult(intent2,2);//采用ForResult打開

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容