gpt4 book ai didi

java - 将图像 URI 转换为文件对象

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

我正在开发一个应用程序,我需要从 SD 卡中选择一个图像并将其发送到 IBM Waston Visual Recognition 服务以识别图像中的内容。我正在这样做..

...
private VisualRecognition service;
private VisualClassification result;
...

private void openImageFromSDCard(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_FILE);
}

private void callIBMWatsonVisualRecognition(){

try {
ContentResolver cr = this.getContentResolver();
InputStream is = cr.openInputStream(image);
File file = new File("Image.jpg");
FileOutputStream fr = new FileOutputStream(file);
int c;
while ((c = is.read()) != -1) {
fr.write(c);
}
result = service.classify(file).execute();
tvResult.setText(result.toString());
is.close();
fr.close();
}catch (Exception e){
Log.d("THINK", "Error = " + e);
}

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {

if (requestCode == SELECT_FILE) {

image = data.getData();
tvResult.setText(image.toString());
imageSelectFlag = true;

}
}
}
...

错误:

java.lang.IllegalArgumentException: image cannot be null or not be found
at com.ibm.watson.developer_cloud.util.Validator.isTrue(Validator.java:38)
at com.ibm.watson.developer_cloud.visual_recognition.v2_beta.VisualRecognition.classify(VisualRecognition.java:152)
at com.ibm.watson.developer_cloud.visual_recognition.v2_beta.VisualRecognition.classify(VisualRecognition.java:124)
at com.algor7.watsonvisiondemo.MainActivity.callIBMWatsonVisualRecognition(MainActivity.java:75)
at com.algor7.watsonvisiondemo.MainActivity.onClick(MainActivity.java:57)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

请检查 VisualRecognition 和 VisualClassification 类 (v2) here

最佳答案

File file = new File(image.toString());

你不是这样的consume content identified by a Uri .要么:

  • 使用 ContentResolveropenInputStream(),然后将 InputStream 传递到您的库中,或者

    <
  • 使用 ContentResolveropenInputStream(),然后使用 Java I/O 将 InputStream 复制到您指定的某个文件控制,然后将该 File 传递到您的库中

关于java - 将图像 URI 转换为文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37321125/

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