android中,远程嗠器为flask;在android中把一张图片,和3个String数据通过okhttp3传递到flask;其中;图片需要一个从拍照和相册中选择,如果是拍照,调用相机;如果是相册,从手机本地的照片中选择,然后再上传.请给出代码
时间: 2024-04-08 10:35:29 浏览: 91
当在Android中使用OkHttp3传递图片和字符串数据到Flask服务器时,可以按照以下步骤进行操作。首先,需要添加权限以及一些必要的库依赖。
1. 在`AndroidManifest.xml`文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 在app级别的`build.gradle`文件中添加OkHttp3和其他必要的库依赖:
```groovy
dependencies {
// Other dependencies
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.github.bumptech.glide:glide:4.12.0'
implementation 'com.github.bumptech.glide:compiler:4.12.0'
}
```
接下来,我们可以编写代码来实现从相机或相册选择照片,然后使用OkHttp3上传到Flask服务器。
```java
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSION = 200;
private static final int REQUEST_IMAGE_CAPTURE = 100;
private static final int REQUEST_IMAGE_PICK = 101;
private ImageView imageView;
private Button cameraButton;
private Button galleryButton;
private Button uploadButton;
private String selectedImagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
cameraButton = findViewById(R.id.cameraButton);
galleryButton = findViewById(R.id.galleryButton);
uploadButton = findViewById(R.id.uploadButton);
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
} else {
openCamera();
}
}
});
galleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGallery();
}
});
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedImagePath != null) {
uploadImage(selectedImagePath);
}
}
});
}
private void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
private void openGallery() {
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent, REQUEST_IMAGE_PICK);
}
private void uploadImage(String imagePath) {
File imageFile = new File(imagePath);
if (imageFile.exists()) {
OkHttpClient client = new OkHttpClient();
// 构建请求体
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
requestBodyBuilder.addFormDataPart("string1", "value1");
requestBodyBuilder.addFormDataPart("string2", "value2");
requestBodyBuilder.addFormDataPart("string3", "value3");
requestBodyBuilder.addFormDataPart("image", imageFile.getName(), RequestBody.create(MediaType.parse("image/*"), imageFile));
// 构建请求
Request request = new Request.Builder()
.url("http://your_flask_server_url")
.post(requestBodyBuilder.build())
.build();
// 发送请求并异步处理响应
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if (response.isSuccessful()) {
// 处理成功响应
String responseData = response.body().string();
Log.d("Upload Response", responseData);
}
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri tempUri = getImageUri(photo);
selectedImagePath = tempUri.getPath();
Glide.with(this).load(tempUri).into(imageView);
} else if (requestCode == REQUEST_IMAGE_PICK) {
Uri selectedImageUri = data.getData();
selectedImagePath = selectedImageUri.getPath();
Glide.with(this).load(selectedImageUri).into(imageView);
}
}
}
private Uri getImageUri(Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}
}
}
}
```
在上面的代码中,我们使用了一个ImageView来显示选择的图片。当用户点击拍照按钮时,会检查相机权限并打开相机应用进行拍照。当用户点击相册按钮时,会打开相册应用来选择照片。上传按钮用于触发上传操作。在`onActivityResult`方法中,我们处理从相机或相册返回的结果,并将选择的图片显示在ImageView中。`getImageUri`方法用于将Bitmap对象保存为临时文件,并返回其URI。
请替换代码中的`http://your_flask_server_url`为你自己的Flask服务器的URL。确保你的Flask服务器端能够处理接收图片和字符串数据的请求,并做相应的处理。
阅读全文