Retrofit+Axjava 上傳頭像(相機+相冊+裁剪)

廢話不多說,直接上代碼了!!

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>



發佈了56 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章