转载请注明出处:https://blog.youkuaiyun.com/qq_36137075/article/details/91362655
相机
private int PHOTO_REQUEST_CAREMA = 0;
private int PHOTO_REQUEST_CUT = 3;
public void Photograph() throws IOException{
outputImage = createFileIfNeed("UserIcon.png");
if (Build.VERSION.SDK_INT >= 24) {
//需要在配置文件配置provider 不明白的可以看我的android安装apk的博客
imageUri = FileProvider.getUriForFile(UserInfoActivity.this, "com.xx.xx.fileProvider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
//启动相机程序
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
}
相册
private void Album() {
Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture, 2);
}
裁剪
private void crop(Uri uri) {
File CropPhoto = new File(getExternalCacheDir(), "crop_image.jpg");
try {
if (CropPhoto.exists()) {
CropPhoto.delete();
}
CropPhoto.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
cropImageUri = Uri.fromFile(CropPhoto);
// 裁剪图片意图
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.putExtra("crop", "true");
// // 裁剪框的比例,1:1
// intent.putExtra("aspectX", 1);
// intent.putExtra("aspectY", 1);
// // 裁剪后输出图片的尺寸大小
// intent.putExtra("outputX", 250);
// intent.putExtra("outputY", 250);
// 裁剪框的比例,4:3
intent.putExtra("aspectX", 4);
intent.putExtra("aspectY", 3);
// 裁剪后输出图片的尺寸大小
intent.putExtra("outputX", 800);
intent.putExtra("outputY", 600);
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());// 图片格式
intent.putExtra("noFaceDetection", true);// 取消人脸识别
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
crop(selectedImage);
}else if (requestCode == PHOTO_REQUEST_CAREMA){
if (resultCode == RESULT_OK){
crop(imageUri);
}else{
}
} else if (requestCode == PHOTO_REQUEST_CUT){
if (data != null) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropImageUri));
profile_image.setImageBitmap(bitmap);
saveImageToServer(bitmap,"");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}