修改为调用摄像机后的代码
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import androidx.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1;
private ImageView imageView;
private TextView textView;
private String accessToken;
private Bitmap selectedImageBitmap;
private static final String BAIDU_API_KEY = "YnFw5LSDvq76bzSdjWuGWlXL";
private static final String BAIDU_SECRET_KEY = "lOa0jDMgcQT0baNlzjIR7GMwCFoFEUUy";
private static final String FACE_DETECT_URL = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
private final OkHttpClient client = new OkHttpClient();
private final Handler handler = new Handler(Looper.getMainLooper());
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonRecordMood = findViewById(R.id.button_record_mood);
buttonRecordMood.setOnClickListener(view -> openCamera());
Button buttonViewRecords = findViewById(R.id.button_view_records);
buttonViewRecords.setOnClickListener(view -> viewRecords());
getAccessTokenAsync();
}
private void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null && requestCode == CAMERA_REQUEST) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
selectedImageBitmap = bitmap;
String imageBase64 = bitmapToBase64(bitmap);
sendFaceDetectRequest(imageBase64);
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
private void getAccessTokenAsync() {
executorService.execute(() -> {
this.accessToken = getAccessToken();
handler.post(() -> {
if (this.accessToken == null) {
Log.e("MainActivity", "Failed to get access token");
}
});
});
}
private void sendFaceDetectRequest(String imageBase64) {
if (accessToken == null) {
Log.e("MainActivity", "Access token is null, cannot send face detect request.");
return;
}
executorService.execute(() -> {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("image", imageBase64);
jsonObject.addProperty("image_type", "BASE64");
jsonObject.addProperty("face_field", "age,beauty,expression");
String jsonStr = new Gson().toJson(jsonObject);
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonStr, mediaType);
Request request = new Request.Builder()
.url(FACE_DETECT_URL + "?access_token=" + this.accessToken)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseStr = response.body().string();
handler.post(() -> {
try {
JSONObject jsonResponse = new JSONObject(responseStr);
JSONObject result = jsonResponse.optJSONObject("result");
if (result != null) {
int age = result.getJSONArray("face_list").getJSONObject(0).getInt("age");
String beauty = result.getJSONArray("face_list").getJSONObject(0).getString("beauty");
String expression = result.getJSONArray("face_list").getJSONObject(0).getString("expression");
String resultText = "Age: " + age + "\nBeauty: " + beauty + "\nExpression: " + expression;
Intent intent = new Intent(MainActivity.this, MoodRecordActivity.class);
intent.putExtra("age", String.valueOf(age)); // 确保年龄是字符串类型
intent.putExtra("beauty", beauty);
intent.putExtra("expression", expression);
intent.putExtra("image", imageBase64);
startActivity(intent);
} else {
Log.e("MainActivity", "Face detect request failed: result is null");
}
} catch (JSONException e) {
e.printStackTrace();
}
});
} else {
Log.e("MainActivity", "Face detect request failed");
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
private String getAccessToken() {
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
RequestBody body = new FormBody.Builder()
.add("grant_type", "client_credentials")
.add("client_id", BAIDU_API_KEY)
.add("client_secret", BAIDU_SECRET_KEY)
.build();
Request request = new Request.Builder()
.url(authHost)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseBody = response.body().string();
JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
return jsonObject.get("access_token").getAsString();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void viewRecords() {
Intent intent = new Intent(this, ViewRecordsActivity.class);
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
executorService.shutdown();
}
}
标签:11,String,private,Intent,new,import,android From: https://www.cnblogs.com/1947475882-/p/18277699