public class MainActivity extendsAppCompatActivity {private final int FROM_ALBUM = 1;//表示从相册获取照片
private final int FROM_CAMERA = 2;//表示从相机获取照片
privateImageView imageView;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
textView=(TextView)findViewById(R.id.textView);
setContentView(R.layout.activity_main);
applyWritePermission();//请求权限
}//打开相册
public voidonClickAlbum(View view){
Intent intent= newIntent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, FROM_ALBUM);
}//打开相机
public voidonClickCamera(View view){
Intent intent= newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, FROM_CAMERA);
}
@Overrideprotected void onActivityResult(int requestCode, intresultCode, Intent data){//从相册返回
if(requestCode == FROM_ALBUM && resultCode == Activity.RESULT_OK && data != null){
imageView=(ImageView)findViewById(R.id.imageView);
textView=(TextView)findViewById(R.id.textView);
Uri imageUri=data.getData();
ContentResolver cr= this.getContentResolver();try{
Bitmap bitmap=BitmapFactory.decodeStream(cr.openInputStream(imageUri));int res =FaceClassified.runClassified(bitmap);
imageView.setImageBitmap(bitmap);
}catch(FileNotFoundException e){
Log.e("Exception", e.getMessage(), e);
}
}//从相机返回
if(requestCode == FROM_CAMERA && resultCode == Activity.RESULT_OK && data != null){
imageView=(ImageView)findViewById(R.id.imageView);
textView=(TextView)findViewById(R.id.textView);
Bitmap photo= (Bitmap) data.getExtras().get("data");int res =FaceClassified.runClassified(photo);
imageView.setImageBitmap(photo);
}super.onActivityResult(requestCode, resultCode, data);
}private voidapplyWritePermission() {
String permissions1=Manifest.permission.WRITE_EXTERNAL_STORAGE;
String permissions2=Manifest.permission.READ_EXTERNAL_STORAGE;
String permissions3=Manifest.permission.CAMERA;if (Build.VERSION.SDK_INT >= 23) {int check1 = ContextCompat.checkSelfPermission(this, permissions1);if (check1 !=PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}int check2 = ContextCompat.checkSelfPermission(this, permissions2);if (check2 !=PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}int check3 = ContextCompat.checkSelfPermission(this, permissions3);if (check3 !=PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
}
}
}
}