网上找了一些代码,我再小米手机上测试,发现还是有的不是很好用,所以找了资料,把代码贴出来分享一下。
[java]
public final static int CONSULT_DOC_PICTURE = 1000;
public final static int CONSULT_DOC_CAMERA = 1001;
private int SELECT_PICTURE = 0;
private int SELECT_CAMERA = 1;
private ImageView iv;
private Bitmap bmp;
private Uri outputFileUri;
[java]
private OnClickListener cameraClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
CharSequence[] items = { "相册", "相机" };
new AlertDialog.Builder(getActivity()).setTitle("选择图片来源").setItems(items, new DialogInte易做图ce.OnClickListener() {
public void onClick(DialogInte易做图ce dialog, int which) {
if (which == SELECT_PICTURE) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "选择图片"), CONSULT_DOC_PICTURE);
} else {
File file = new File(Environment.getExternalStorageDirectory(), "textphoto.jpg");
outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CONSULT_DOC_CAMERA);
}
}
}).create().show();
}
};
[java]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ConsultDoctor.CONSULT_DOC_PICTURE) {
if(data == null){
return;
}
Uri uri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, proj, // Which
// columns
// to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
if (bmp != null)// 如果不释放的话,不断取图片,将会内存不够
bmp.recycle();
bmp = BitmapFactory.decodeFile(path);
iv.setImageBitmap(bmp);
} else if (requestCode == ConsultDoctor.CONSULT_DOC_CAMERA) {
bmp = BitmapFactory.decodeFile(outputFileUri.getPath());
iv.setImageBitmap(bmp);
} else {
Toast.makeText(getActivity(), "请重新选择图片", Toast.LENGTH_SHORT).show();
}
}
我的代码是写在Fragment里面的。so... 你们懂的