gpt4 book ai didi

android - ACTION_IMAGE_CAPTURE - 在默认位置拍照后获取 URI

转载 作者:行者123 更新时间:2023-11-29 01:26:37 26 4
gpt4 key购买 nike

我正在拍摄如下照片:

activity.startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), BaseDef.REQUEST_CODE_CAMERA);

之后,我只想获取新图像路径、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();
}
}
}

但是 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;
}
}
}
}

最佳答案

注意:针对 api-24 或更高版本,see here .

针对 api-23 或更低版本:

执行此操作的最佳方法是发送带有用于打开相机的 Intent 的 Uri。您将需要创建一个临时文件,该文件将被拍摄的照片覆盖。

首先声明一个成员变量来存放Uri:

public class MyPhotoActivity extends AppCompatActivity {

Uri uri;
//.............

设置临时文件并将 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);
}

然后,如果您在 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
}
}
}

关于android - ACTION_IMAGE_CAPTURE - 在默认位置拍照后获取 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33666026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com