调用相机或相册:
dialog.setOnUploadHeadClickListener(new UploadHeadDialog.OnUploadHeadClickListener() {
@Override
public void onCreamClick(View v) {
// 调用相机 返回Uri
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, headUri);
startActivityForResult(intent, PHOTO_REQUEST_XIANGJI);
isAvatarChange = true;
}
@Override
public void onPictureClick(View v) {
// 开启相册并剪辑
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setType("image/*"); //调用的是系统图库
intent.putExtra(MediaStore.EXTRA_OUTPUT, headUri);
startActivityForResult(intent, PHOTO_REQUEST_XIANGCE);
isAvatarChange = true;
}
});
获取相机或相册返回的照片:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PHOTO_REQUEST_XIANGCE:
// 从相册返回数据
Uri uri = data.getData();
// 剪切图片
cropImageUri(uri);
break;
case PHOTO_REQUEST_XIANGJI:
// 从相机返回的数据
cropCamImageUri(headUri);
break;
case CROP_PICTURE_XIANGCE:
//获取相册剪切后的图片
Bitmap bitmap = decodeUriAsBitmap(headUri);
if (bitmap != null) {
iv_avatar.setImageBitmap(bitmap);
// 七牛生成token并上传图片
getQiniuToken();
}
break;
case CROP_PICTURE_XIANGJI:
if (headUri != null) {
Bitmap bitmap2 = decodeUriAsBitmap(headUri);
if (bitmap2 != null) {
iv_avatar.setImageBitmap(bitmap2);
// 七牛生成token并上传图片
getQiniuToken();
}
} else {
Log.e(Constants.TAG, "CROP_SMALL_PICTURE: data = " + data);
}
break;
}
}
剪切图片:
private void cropImageUri(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, headUri);
startActivityForResult(intent, CROP_PICTURE_XIANGCE);
}
private void cropCamImageUri(Uri uri) {
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", 400);
intent.putExtra("outputY", 400);
intent.putExtra("scale", true);
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, CROP_PICTURE_XIANGJI);
}
获取剪切后的图片:
private Bitmap decodeUriAsBitmap(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return bitmap;
}