获取相机拍摄的uri照片 [英] Get uri of picture taken by camera
问题描述
当用户使用相机拍摄照片时,我希望图像显示在ImageView中,并且要将Uri保存到在线数据库中.我听说保存图片的Uri比保存路径更好.
When the user takes a picture with the camera, I want the image displayed in an ImageView and I want to save the Uri to an online database. I heard saving the Uri of a picture is better than saving the path.
这就是我启动相机的方式:
So this is how I start the camera:
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getFile(getActivity())));
String a = String.valueOf(Uri.fromFile(getFile(getActivity())));
intent.putExtra("photo_uri", a);
startActivityForResult(intent, PICK_FROM_CAMERA);
其中
private File getFile(Context context){
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Myapp");
if (!directory.exists()) {
directory.mkdirs();
}
String filename = "bl" + System.currentTimeMillis() + ".jpg";
File newFile = new File(directory, filename);
return newFile;
}
在onActivityResult中:
In onActivityResult:
Bundle extras = data.getExtras();
String photo_uri = extras.getString("photo_uri"); //null
这始终为空.顺便说一句,在发送意图之前,Uri看起来像file://...而不是content://,这是我从图库中打开图像时的uri.我不知道这是否有问题.
This is always null. Btw before sending the intent the Uri looks like file://... instead of content:// which is the uri when I open an image from the gallery. I don't know if that's a problem.
此外,我应该将路径而不是Uri保存到数据库吗?我读到Uri在某些手机或Android版本中可能会很复杂.当我让用户从图库中选择图像时,我会将Uri保存到数据库中,因此我认为最好的方法就是在这种情况下也保存Uri.
Also, should I save the path instead of the Uri to the database? I read that the Uri can be complicated in certain phones or Android versions. When I let the user select an image from the gallery, I save the Uri to the database, so I think the best way is saving the Uri in this case as well.
我尝试了许多变体,但是每次尝试有意图地传递变量时,我都会得到null ...
I tried out many variations, but I get null every time I try to pass a variable with the intent...
推荐答案
启动意图后:
Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentPicture,PICK_FROM_CAMERA);
在onActivityResult
中:
case PICK_FROM_CAMERA:
Uri selectedImageUri = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
break;
仅此而已.
这篇关于获取相机拍摄的uri照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!