okhttp+retrofit+rxjava上传头像+裁剪

注:个人记录

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

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

//请求码
private static final int MY_ADD_CASE_CALL_PHONE = 6;
private static final int MY_ADD_CASE_CALL_PHONE2 = 7;
private static final int TAKE_PICTURE = 1;
private static final int CHOOSE_PICTURE = 2;
private static final int CROP_SMALL_PICTURE = 3;

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

/**
 *  相机的按钮
 */
xj_pop.setOnClickListener(new View.OnClickListener() {
    @Override
    public 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() {
    @Override
    public 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);
}

Okhttp的封装类

public class OkHttp {

    public final Api api;

    private static class OkHttpInstance{
        private static OkHttp okHttp = new OkHttp();
    }

    public static OkHttp getInstance(){
        return OkHttpInstance.okHttp;
    }

    private OkHttp(){

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .build();

        Gson gson = new GsonBuilder().setLenient().create();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(BaseUrl.RZ_URL)
                .build();
        api = retrofit.create(Api.class);

    }

    /**
     * 网络判断
     * @param context
     * @return
     */
    public boolean netWork(Context context){
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null){
            return networkInfo.isAvailable();
        }
        return false;
    }

}

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

//上传文件
@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>() {
                @Override
                public void accept(UpLoadFile upLoadFile) throws Exception {
                    getView().onSuccess(upLoadFile);
                }
            }, new Consumer<Throwable>() {
                @Override
                public 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>() {
                @Override
                public void accept(SetUserInfo setUserInfo) throws Exception {
                    getView().onSuccess(setUserInfo);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    getView().onError(throwable.toString());
                }
            });
}

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

你可能感兴趣的:(okhttp+retrofit+rxjava上传头像+裁剪)