pro*_*m85 5 camera android uri image
我正在拍摄如下照片:
activity.startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), BaseDef.REQUEST_CODE_CAMERA);
Run Code Online (Sandbox Code Playgroud)
之后,我只想获取新的图像路径、uri 或类似的(不是位图或图像数据),以便我知道新图像的位置。因此,我尝试检索 uri,如下所示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == BaseDef.REQUEST_CODE_CAMERA)
{
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但 uri 有时是null. 如何在此类设备上获取图像路径/uri?
编辑
我真的想保留使用任何相机应用程序创建的默认文件名!
当前的解决方法(我不知道这是否总是有效):
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == BaseDef.REQUEST_CODE_CAMERA)
{
if (resultCode == RESULT_OK)
{
String path = null;
Uri uri = data.getData();
if (uri != null)
path = MediaUtil.getRealPathFromURI(uri);
else
{
L.d(this, "URI == NULL => trying to get last image path directly");
// here I just sort mediastore by id desc and get the first image's path
// can I be sure this ALWAYS works?
// When the camera returns, the image SHOULD be already in the media store
// If not, I would get a wrong image...
path = MediaStoreUtil.getLastImagePath();
}
if (path == null)
{
L.d(this, "Path of camera image could not be retrieved");
return;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意: 要了解针对 api-24 或更高版本的信息,请参阅此处。
对于定位 api-23 或更低版本:
最好的方法是发送包含用于打开相机的 Intent 的 Uri。您将需要创建一个临时文件,该文件将被拍摄的照片覆盖。
首先,声明一个成员变量来存储 Uri:
public class MyPhotoActivity extends AppCompatActivity {
Uri uri;
//.............
Run Code Online (Sandbox Code Playgroud)
设置临时文件并将 Uri 传递给相机应用程序:
public void takePhoto() {
counter++; //this is an int
String imageFileName = "JPEG_" + counter; //make a better file name
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName,
".jpg",
storageDir
);
uri = Uri.fromFile(image);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(takePhotoIntent, BaseDef.REQUEST_CODE_CAMERA);
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您在 onActivityResult() 中获得成功结果,则创建的临时文件包含捕获的图像,您可以将其用于uri您需要的任何内容:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == BaseDef.REQUEST_CODE_CAMERA)
{
if (resultCode == RESULT_OK)
{
//use uri member variable...
//it has the image that was captured
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5634 次 |
| 最近记录: |