编辑:好的,这是我最后一次尝试这个,新代码相同的结果。我在ImageView中获得了一个图像,但没有来自服务器的任何返回字符串的迹象。
这是服务器期望得到的(图像可以是url或base64编码的图像):
POST /detect HTTP/1.1
Content-Type: application/json
app_id: 4985f625
app_key: aa9e5d2ec3b00306b2d9588c3a25d68e
{
"image":" http://media.kairos.com/kairos-elizabeth.jpg ",
"selector":"ROLL"
}
这是我的代码: MainActivity.java
public class MainActivity extends AppCompatActivity {
EncodeToBase64 encode = new EncodeToBase64();
String lastPhotoAsBase64;
ImageView mImageView;
String path = Environment.getExternalStorageDirectory().toString() + "/files/Pictures";
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
String mTestPath = "/storage/emulated/0/Android/data/com.example.cliff.camera2/files/Pictures/JPEG_20171209_174301_1623885500.jpg";
String jsonResult;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
Button cameraButton = findViewById(R.id.cameraButton);
textView = findViewById(R.id.textView);
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
setPic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
public void setPic() throws IOException {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
//BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ExifInterface exif = new ExifInterface(mCurrentPhotoPath);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
//int deg = rotationInDegrees;
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
lastPhotoAsBase64 = encode.encode(bitmap);
if(lastPhotoAsBase64 != null) {
new postData().execute(lastPhotoAsBase64);
}
else{
Toast.makeText(MainActivity.this,"No base64 data found!",Toast.LENGTH_LONG).show();
}
mImageView.setImageBitmap(bitmap);
}
public void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
public class postData extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... strings) {
HttpConnectionActivity hh = new HttpConnectionActivity();
String temp = hh.HttpConnection(strings[0]);
textView.setText(temp);
textView.setVisibility(View.VISIBLE);
return null;
}
}
}
HttpConnectionActivity.java
public class HttpConnectionActivity {
private final static String KAIROS_URL = "https://api.kairos.com/detect";
private final String KEY = "5232cdde7e35d8de7ac78726060d5a01";
private final String ID = "9bd755a1";
String serverResponse;
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
JSONObject postdata = new JSONObject();
public String HttpConnection(String image) {
OkHttpClient client = new OkHttpClient();
try {
postdata.put("image", image);
RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());
final Request request = new Request.Builder()
.url(KAIROS_URL)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("app_id", ID)
.addHeader("app_key", KEY)
.build();
Response response = client.newCall(request).execute();
serverResponse = response.body().string();
} catch (Exception ex) {
ex.getMessage();
}
return serverResponse;
}
}
EncodeToBase64.java
public class EncodeToBase64 {
public String encode(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
}
OnCustomEventListener.java
public interface OnCustomEventListener {
public void onEvent();
}