实现安卓拍照上传至服务器的功能需要以下几个步骤:
1.获取摄像头权限:在AndroidManifest.xml中添加以下权限
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2.调用摄像头:使用Intent调用系统的相机应用
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
3.获取照片:在onActivityResult方法中获取拍摄的照片
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
}
4.将Bitmap转为File:为了上传到服务器,我们需要把Bitmap转为File
public File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "tempfile.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
5.上传图片:将图片转换为MultipartBody.Part类型,并配置Retrofit进行图片上传
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
retrofit.create(service.class).postImage(body, name).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//上传成功处理
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
上述代码中的service.class是你自定义的接口,postImage方法是你的上传图片的接口,body是你的图片,需要上传到服务器的,name是上传图片的名字。上传成功后的操作在onResponse里面处理,如保存返回的url,显示上传的图片等。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/171877.html