当前位置: 代码迷 >> 综合 >> okhttp+retrofit上传头像+裁剪
  详细解决方案

okhttp+retrofit上传头像+裁剪

热度:5   发布时间:2024-01-25 10:29:46.0

这一篇是衔接了上一篇pop弹窗
上一篇地址:

https://blog.csdn.net/a506656675/article/details/103716703

这里的按钮是 pop自定义布局 的按钮
简洁明了:相机的按钮

/*** 相机的按钮*/
xj_pop.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {// 6.0之后动态申请权限 摄像头调取权限,SD卡写入权限if (ContextCompat.checkSelfPermission(MyMsgActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED&& ContextCompat.checkSelfPermission(MyMsgActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(MyMsgActivity.this,new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_ADD_CASE_CALL_PHONE);} else {try {//有权限,去打开摄像头takePhoto();} catch (IOException e) {e.printStackTrace();}}popupWindow.dismiss();}
});

相册的按钮

/*** 相册机的按钮*/
xc_pop.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {// 6.0之后动态申请权限 SD卡写入权限if (ContextCompat.checkSelfPermission(MyMsgActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(MyMsgActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_ADD_CASE_CALL_PHONE2);} else {//有权限,去打开相册choosePhoto();}popupWindow.dismiss();}
});
/*** 相机** @throws IOException*/
private void takePhoto() throws IOException {Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);tempUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp_image.jpg"));// 将拍照所得的相片保存到SD卡根目录openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);startActivityForResult(openCameraIntent, TAKE_PICTURE);}
/*** 打开相册*/
private void choosePhoto() {Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);openAlbumIntent.setType("image/*");//用startActivityForResult方法,待会儿重写onActivityResult()方法,拿到图片做裁剪操作startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);}

下面是裁剪和回调:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK) {switch (requestCode) {case TAKE_PICTURE:cutImage(tempUri); // 对图片进行裁剪处理break;case CHOOSE_PICTURE:cutImage(data.getData()); // 对图片进行裁剪处理break;case CROP_SMALL_PICTURE:if (data != null) {setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上}break;}}
}/*** 裁剪图片方法实现*/
protected void cutImage(Uri uri) {if (uri == null) {Log.i("dyp", "The uri is not exist.");}tempUri = uri;Intent intent = new Intent("com.android.camera.action.CROP");//com.android.camera.action.CROP这个action是用来裁剪图片用的intent.setDataAndType(uri, "image/*");// 设置裁剪intent.putExtra("crop", "true");// aspectX aspectY 是宽高的比例intent.putExtra("aspectX", 1);intent.putExtra("aspectY", 1);// outputX outputY 是裁剪图片宽高intent.putExtra("outputX", 150);intent.putExtra("outputY", 150);intent.putExtra("return-data", true);startActivityForResult(intent, CROP_SMALL_PICTURE);
}/*** 保存裁剪之后的图片数据*/
protected void setImageToView(Intent data) {Bundle extras = data.getExtras();if (extras != null) {mBitmap = extras.getParcelable("data");File file = getFile(mBitmap);//调用接口,上传头像presenter.upLoadFile(user_token , file);//调用接口,保存头像 //presenter.setUserAvatar(user_token , origin_name , path);//头像设置为新的图片Glide.with(this).load(mBitmap).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(imgMyMsg);}
}/*** Bitmap 转 file* @param bitmap* @return*/
public File getFile(Bitmap bitmap) {ByteArrayOutputStream baos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);File file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");try {file.createNewFile();FileOutputStream fos = new FileOutputStream(file);InputStream is = new ByteArrayInputStream(baos.toByteArray());int x = 0;byte[] b = new byte[1024 * 100];while ((x = is.read(b)) != -1) {fos.write(b, 0, x);}fos.close();} catch (Exception e) {e.printStackTrace();}return file;
}/*** 申请权限回调** @param requestCode* @param permissions* @param grantResults*/@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {if (requestCode == MY_ADD_CASE_CALL_PHONE) {if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {try {takePhoto();} catch (IOException e) {e.printStackTrace();}} else {//"权限拒绝");// TODO: 这里可以给用户一个提示,请求权限被拒绝了}}if (requestCode == MY_ADD_CASE_CALL_PHONE2) {if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {choosePhoto();} else {//"权限拒绝");// TODO: 这里可以给用户一个提示,请求权限被拒绝了}}super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

我这里是用的两个接口,一个是 先把头像上传至服务器,然后再保存头像

//上传文件
@POST("api/utility/uploadFile")
@Multipart//注意这个
Observable<UpLoadFile> uploadFile(@Query("token")String token ,@Part MultipartBody.Part MultipartFile);
//保存头像
@GET("api/user/setUserAvatar")
Observable<SetUserInfo> setUserAvatar(@Query("token")String token ,@Query("origin_name")String origin_name ,@Query("path")String path);

P层的处理:

//上传文件
public void upLoadFile(String token , File file){RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);MultipartBody.Part MultipartFile = MultipartBody.Part.createFormData("picture", file.getName(), requestFile);Observable<UpLoadFile> upLoadfile = okHttp.api.uploadFile(token, MultipartFile);upLoadfile.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<UpLoadFile>() {@Overridepublic void accept(UpLoadFile upLoadFile) throws Exception {getView().onSuccess(upLoadFile);}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable throwable) throws Exception {getView().onError(throwable.toString());}});
}
//保存头像
public void setUserAvatar(String token , String origin_name , String path){Observable<SetUserInfo> setUserInfo = okHttp.api.setUserAvatar(token, origin_name, path);setUserInfo.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<SetUserInfo>() {@Overridepublic void accept(SetUserInfo setUserInfo) throws Exception {getView().onSuccess(setUserInfo);}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable throwable) throws Exception {getView().onError(throwable.toString());}});
}

清单文件的读取和写入的权限也要加。

  相关解决方案