// 上传图片
private CharSequence[] items = { "选择本地图片", "拍照" };
private final int SELECT_LOCAL = 0, SELECT_CAMER = 1, PICTURE_CROP = 2,
PICTURE_FRESH = 3;
/**
* 修改个人图片
*/
public void modifyPhoto() {
Builder builder = new AlertDialog.Builder(mContext);
AlertDialog dialog = builder.setTitle("请选择图片来源")
.setItems(items, new PhotoDialogClickListener()).create();
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
dialog.show();
}
/**
* 选择对话框
*/
private class PhotoDialogClickListener implements
DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case SELECT_LOCAL:
methodURI(which);
break;
case SELECT_CAMER:
methodURI(which);
break;
default:
break;
}
}
}
/**
* 适合S3, 小米
*
* @param intent
* @param requestCode
*/
private void methodURI(int requestCode) {
Intent intent = null;
switch (requestCode) {
case SELECT_LOCAL:
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "选择图片"),
SELECT_LOCAL);
break;
case SELECT_CAMER:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, SELECT_CAMER);
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
Uri uri = data.getData();
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
if (requestCode == SELECT_LOCAL || requestCode == SELECT_CAMER) {
if (uri != null) {
startPictureCrop(data.getData());
} else if (extras != null) {
updateView(data);
}
} else if (requestCode == PICTURE_CROP && data != null) {
updateView(data);
}
}
}
/**
* 更新photo
*
* @param data
*/
private void updateView(Intent data) {
Bundle extras = data.getExtras();
if (extras != null) {
new Thread(new PictureThread(extras)).start();
}
}
class PictureThread implements Runnable {
private Bundle bundle;
public PictureThread(Bundle extras) {
bundle = extras;
}
@Override
public void run() {
Message msg = new Message();
msg.what = PICTURE_FRESH;
msg.setData(bundle);
uploadHeadPhoto(bundle);
}
}
/**
* 开始裁剪图片
*
* @param pictureUri
* 图片URI
*/
private void startPictureCrop(Uri pictureUri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(pictureUri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, PICTURE_CROP);
}