Retrofit+Axjava 上传头像(相机+相册+裁剪)

本文通过Retrofit结合Glide库,详细展示了如何实现从相机和相册选择图片并进行裁剪,然后上传头像的功能。包括Activity的实现、Retrofit接口定义、Util工具类的使用以及相关布局文件的设计。
摘要由CSDN通过智能技术生成

废话不多说,直接上代码了!!

activity

private SimpleDraweeView mine_zi_liao_userPhoto;
private TextView mine_zi_liao_mobile;
private TextView mine_zi_liao_username;
private PopupWindow mPopupWindowDialog;
private Button btn_take_photo;
private Button btn_pick_photo;
private Button btn_cancel;
private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
private static final int PHOTO_REQUEST_CUT = 3;// 结果

   //点击弹出 popwindow 弹框
public void mine_zi_liao_userPhotos(View view) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View vi = inflater.inflate(R.layout.userphotopopwindow, null);
        btn_take_photo = (Button) vi.findViewById(R.id.btn_take_photo);
        btn_pick_photo = (Button) vi.findViewById(R.id.btn_pick_photo);
        btn_cancel = (Button) vi.findViewById(R.id.btn_cancel);
        btn_take_photo.setOnClickListener(this);
        btn_pick_photo.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        /*pop 设置*/
        mPopupWindowDialog = new PopupWindow(vi, ActionBar.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
        mPopupWindowDialog.setFocusable(true);
        mPopupWindowDialog.update();
        mPopupWindowDialog.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindowDialog.setOutsideTouchable(true);
        /*显示 pop 弹框*/
        mPopupWindowDialog.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

}
/*选择弹框选项*/
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_take_photo:// 拍照
            // 激活相机
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            // 判断存储卡是否可以用,可用进行存储
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
                // 从文件中创建uri
                Uri uri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
            startActivityForResult(intent, PHOTO_REQUEST_CAREMA);

            if (mPopupWindowDialog != null && mPopupWindowDialog.isShowing()) {
                mPopupWindowDialog.dismiss();
            }
            break;
        case R.id.btn_pick_photo:// 相册
            // 激活系统图库,选择一张图片
            Intent intent1 = new Intent(Intent.ACTION_PICK);
            intent1.setType("image/*");
            // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
            startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);

            if (mPopupWindowDialog != null && mPopupWindowDialog.isShowing()) {
                mPopupWindowDialog.dismiss();
            }
            break;
        case R.id.btn_cancel: // 取消
            if (mPopupWindowDialog != null && mPopupWindowDialog.isShowing()) {
                mPopupWindowDialog.dismiss();
            }
            break;

    }
}
/**
   * 返回结果
   */
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == PHOTO_REQUEST_GALLERY) {
          // 从相册返回的数据
          if (data != null) {
              // 得到图片的全路径
              Uri uri = data.getData();
              crop(uri);
          }
      } else if (requestCode == PHOTO_REQUEST_CAREMA) {
          //            // 从相机返回的数据
          if (hasSdcard()) {
              crop(Uri.fromFile(tempFile));
          } else {
              Toast.makeText(MineZiLiaoActivity.this, "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show();
          }
      } else if (requestCode == PHOTO_REQUEST_CUT) {
          // 从剪切图片返回的数据
          if (data != null) {
              Bitmap bitmap = data.getParcelableExtra("data");
              /**
               * 获得图片
               */
              mine_zi_liao_userPhoto.setImageBitmap(bitmap);
              //保存到SharedPreferences
              saveBitmapToSharedPreferences(bitmap);
          }
          try {
              // 将临时文件删除
              tempFile.delete();
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      super.onActivityResult(requestCode, resultCode, data);
  }

  /*
   * 判断sdcard是否被挂载
   */
  private boolean hasSdcard() {
      //判断SD卡手否是安装好的   media_mounted
      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
          return true;
      } else {
          return false;
      }
  }
  /*
   * 剪切图片
   */
  private void crop(Uri uri) {
      // 裁剪图片意图
      Intent intent = new Intent("com.android.camera.action.CROP");
      intent.setDataAndType(uri, "image/*");
      intent.putExtra("crop", "true");
      // 裁剪框的比例,1:1
      intent.putExtra("aspectX", 1);
      intent.putExtra("aspectY", 1);
      // 裁剪后输出图片的尺寸大小
      intent.putExtra("outputX", 250);
      intent.putExtra("outputY", 250);

      intent.putExtra("outputFormat", "JPEG");// 图片格式
      intent.putExtra("noFaceDetection", true);// 取消人脸识别
      intent.putExtra("return-data", true);
      // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
      startActivityForResult(intent, PHOTO_REQUEST_CUT);
  }

  //保存图片到SharedPreferences
  private void saveBitmapToSharedPreferences(Bitmap bitmap) {
      // Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
      //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
      //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
      byte[] byteArray = byteArrayOutputStream.toByteArray();
      String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));

      //第三步:将String保持至SharedPreferences
      SharedPreferences sharedPreferences = getSharedPreferences("huangxiaoer", Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedPreferences.edit();
      editor.putString("image", imageString);
      editor.commit();

      //上传头像
      setImgByStr(bitmap);
  }

  /**
   * 上传头像
   */
  public void setImgByStr(Bitmap bitmap) {
      if (bitmap != null) {
          // 拿着imagePath上传了
      }
      String imagePath = ImageUtil.savePhoto(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));

      File file = new File(imagePath);//将要保存图片的路径
      try {
          BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
          bos.flush();
          bos.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
      RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file);
      photouri = MultipartBody.Part.createFormData("file", file.getName(), photoRequestBody);

      /*头像*/
      presenter.getPuserphoto(uid, photouri);
  }
//这个看自己的需求,需要时添加即可
  /*  //从SharedPreferences获取图片
   private void getBitmapFromSharedPreferences() {
        SharedPreferences sharedPreferences = getSharedPreferences("testSP", Context.MODE_PRIVATE);
        //第一步:取出字符串形式的Bitmap
        String imageString = sharedPreferences.getString("image", "");
        //第二步:利用Base64将字符串转换为ByteArrayInputStream
        byte[] byteArray = Base64.decode(imageString, Base64.DEFAULT);
        if (byteArray.length == 0) {
            mine_zi_liao_userPhoto.setImageResource(R.mipmap.ic_launcher);
        } else {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
            //第三步:利用ByteArrayInputStream生成Bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
            mine_zi_liao_userPhoto.setImageBitmap(bitmap);

        }

    }
*/

retrofit 请求数据

/*上传图片*/
public void getMUserphoto(int uid, MultipartBody.Part photouri) {
    RetrofitApi retrofitInterface = RetrofitUtil.getInstance().getRetrofitInterface();
    Observable<UserPhotoBean> user = retrofitInterface.getUserPhotoBean(uid, photouri);
    user.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<UserPhotoBean>() {
        @Override
        public void onSubscribe(Disposable d) {
        }
        @Override
        public void onNext(UserPhotoBean userPhotoBean) {
        }
        @Override
        public void onError(Throwable e) {
        }
        @Override
        public void onComplete() {
        }
    });
}



APi 接口

 
/**
 * 上传头像
 * https://www.zhaoapi.cn/file/upload?uid=15005&file=?
 */
@POST("file/upload")
@Multipart
Observable<UserPhotoBean> getUserPhotoBean(@Query("uid") int uid, @Part MultipartBody.Part file);

retrofitutil工具类

public class RetrofitUtil {
    private Retrofit retrofit;
    private static RetrofitUtil retrofitUtil;

    private RetrofitUtil() {
    }

    private RetrofitUtil(String baseUrl) {
        //第三方的日志拦截器
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //OKhttp3  设置拦截器打印日志
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .addInterceptor(logInterceptor)

                .build();
        retrofit = new Retrofit.Builder().baseUrl(baseUrl) //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava2平台
                .client(okHttpClient)//OKhttp3添加到Retrofit
                .build();
    }

    //可指定baseUrl
    public static RetrofitUtil getInstance(String baseUrl) {
        if (retrofitUtil == null) {
            synchronized (RetrofitUtil.class) {
                if (null == retrofitUtil) {
                    retrofitUtil = new RetrofitUtil(baseUrl);
                }
            }
        }
        return retrofitUtil;
    }
    //默认的baseUrl
    public static RetrofitUtil getInstance() {
        if (null == retrofitUtil) {
            return getInstance("网址一部分, 要和Api 里进行拼接  例如 https://www.zhaoapi.cn/");
        }
        return retrofitUtil;
    }

    //获得Retrofit
    public Retrofit getRetrofit() {
        return retrofit;
    }

    //直接获得RetrofitInterface
    public RetrofitApi getRetrofitInterface() {
        RetrofitApi apiService = retrofit.create(RetrofitApi.class);
        return apiService;
    }
}

xml 布局

 
<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/mine_zi_liao_userPhoto"
    android:layout_width="65dp"
    android:layout_height="59dp"
    android:layout_alignParentEnd="true"
    android:layout_marginEnd="33dp"
    android:layout_marginTop="@dimen/dp_25"
    android:background="@drawable/youxiang"
    android:onClick="mine_zi_liao_userPhotos" />


popwindow布局

<LinearLayout
    android:id="@+id/pop_layout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:gravity="center_horizontal">


    <Button
        android:id="@+id/btn_take_photo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="20dip"
        android:text="拍照"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_pick_photo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="5dip"
        android:text="从相册选择"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dip"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="15dip"
        android:text="取消"
        android:textColor="#ffffff"
        android:textStyle="bold"

        />
</LinearLayout>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值