gpt4 book ai didi

java - 无法获取捕获的图像 uri

转载 作者:行者123 更新时间:2023-12-01 17:30:17 26 4
gpt4 key购买 nike

我正在尝试获取捕获的图像 Uri,但没有在下面的代码中获取如何获取 uri。 Toast 消息给我空结果

 Button b=findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,2);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(Authentication.this,""+data.getData(),Toast.LENGTH_LONG).show();
}

最佳答案

从 Android 版本 LOLLIPOP 中,出于安全原因,您无法直接获取 URI,请尝试此操作 -

    private static Uri getSharableImageUri(Context context) {
File outputDir = context.getCacheDir();
File imagePath = new File(outputDir, context.getString(R.string.app_name));
if (!imagePath.exists()) {
imagePath.mkdir();
}
File tempFile = new File(imagePath, "image.jpg");
Uri uri = null;
try {
if (!tempFile.exists()) {
tempFile.createNewFile();
}
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", tempFile);
} catch (Exception e) {
e.printStackTrace();
}
return uri;
}

并在按钮的点击监听器中使用此-

     Button b=findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {

mImageCaptureUri = getSharableImageUri(context);
}
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
intent.setClipData(ClipData.newRawUri("", mImageCaptureUri));

}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);

} catch (Exception e) {
e.printStackTrace();
}
}
});

}

如果结果成功,则在onActivityResult中获取URI -

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode==2) {
Toast.makeText(Authentication.this,""+data.getData(),Toast.LENGTH_LONG).show();
}

关于java - 无法获取捕获的图像 uri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61135279/

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