//Android中从图库和相机拍照选择图片示例
public class MainActivity extends Activity {
private static final int FROM_GALLERY = 100;// 图库请求码
private static final int FROM_CAMERA = 101;// 相机请求码
private ImageView showimage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.showimage = (ImageView) this.findViewById(R.id.showimage);
}
public void clickButton(View view) {
switch (view.getId()) {
case R.id.but_gallery:
startGallery();
break;
case R.id.but_camera:
startCamera();
break;
}
}
// 点击相机选择按钮
private void startCamera() {
Intent intent = new Intent();
intent.setAction("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, FROM_CAMERA);
}
// 选择从图库中选择按钮
private void startGallery() {
Intent intent = new Intent();
// intent.ACTION_PICK="android.intent.action.PICK"
intent.setAction(intent.ACTION_PICK);
intent.setType("image/*");// 要设置数据类型,不然会出错
startActivityForResult(intent, FROM_GALLERY);
}
// 选择图片返回值的接收
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK || data == null) {
Toast.makeText(this, "您没有选择图片!!", Toast.LENGTH_SHORT).show();
return;
}
// 图库中返回判断
if (requestCode == FROM_GALLERY) {
// 从图库中返回后的数据,使用contentResolverd内容解析器
Uri uri = data.getData();
ContentResolver contentResolver = getContentResolver();
try {
// 转为流
InputStream is = contentResolver.openInputStream(uri);
// 再将流转为位图
Bitmap bitmap = BitmapFactory.decodeStream(is);
showimage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 相机中返回判断
if (requestCode == FROM_CAMERA) {
Bitmap bitmap = data.getParcelableExtra("name");
showimage.setImageBitmap(bitmap);
}
}
}
转载于:https://my.oschina.net/u/2541146/blog/603757