我已经为这个问题绞尽脑汁了一段时间了,如果有人能帮我解决这个问题,我会非常感激。
我试图上传一个图像到沃森的视觉识别API使用POST从Android (通过使用相机拍照)。
在用相机拍照后,我设法保存图像,并将其显示为应用程序上的位图图像。
我正在尝试将文件上传到Watson API,但是我一直收到这个错误
“描述”:“无效的图像数据。支持的格式是JPG、PNG和GIF。”
如果有人能提供一些关于我在这里做错了什么的见解,我将非常感激。提前感谢!
我现在正在使用HttpUrlConnection和DataOutputStream发布文章,代码如下:
imgName和imgPath都是正确识别的,name="images_file“是沃森视觉识别API请求的名称。
public void uploadImage(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=APIKEY&version=2016-05-20");
conn= (HttpURLConnection) url.openConnection();
FileInputStream fileInputStream = new FileInputStream(file);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("images_file", imgPath);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"images_file\"; filename = \"" + imgName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) !=null) {
sb.append(output);
}
Log.d("debugging", sb.toString());
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+imgName;
Toast.makeText(getApplicationContext(), "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Debugging", "Exception : "
+ e.getMessage(), e);
}
Log.d("Debugging", "responseCode:" + serverResponseCode);
}
发布于 2016-08-07 12:10:58
视觉识别在Java中有一个SDK(客户端库)。只需将依赖项添加到build.gradle
中即可。
compile 'com.ibm.watson.developer_cloud:java-sdk:3.2.0'
然后
VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
service.setApiKey("<api-key>");
ClassifyImagesOptions options = new ClassifyImagesOptions.Builder()
.images(new File("car.png"))
.build();
VisualClassification result = service.classify(options)
.enqueue(new ServiceCallback<List<Dialog>>() {
@Override
public void onResponse(List<Dialog> response) {
System.out.println(response);
}
@Override
public void onFailure(Exception e) {
// on failure
}}
);
这个示例有一个带有实用方法的CameraHelper
类,用于获取Android中图片的文件路径或InputStream。
发布于 2016-08-08 15:59:25
另一件必须确保检查的事情是,imgName实际上以其中一个扩展结束--否则系统当前将不接受它。
https://stackoverflow.com/questions/38811303
复制