1. 程式人生 > >安卓開發呼叫相機和本地相簿選擇照片並上傳(上傳retrofit實現)

安卓開發呼叫相機和本地相簿選擇照片並上傳(上傳retrofit實現)

private File tempFile = new File(Environment.getExternalStorageDirectory(),
        getPhotoFileName());

// 使用系統當前日期加以調整作為照片的名稱
private String getPhotoFileName() {
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "'IMG'_yyyyMMdd_HHmmss");
    return dateFormat.format(date) + ".jpg";
}

@OnClick({R.id.person_home_icon, R.id.mine_fra_person_info_rel})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.person_home_icon:
        case R.id.mine_fra_person_info_rel:
            mDialog = new AlertDialog.Builder(mContext, R.style.FullScreenDialog)
                    .create();
            if (mDialog != null && !mDialog.isShowing()) {
                mDialog.show();
                mDialog.setContentView(R.layout.dialog_select_imge);
                mDialog.setCanceledOnTouchOutside(true);
                Window window = mDialog.getWindow();
                window.setGravity(Gravity.BOTTOM);
                tvTakePhoto = (TextView) window.findViewById(R.id.take_photo);
                tvTakePhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent cameraintent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        // 指定呼叫相機拍照後照片的儲存路徑
                        cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(tempFile));
                        startActivityForResult(cameraintent,
                                PHOTO_REQUEST_TAKEPHOTO);
                    }
                });
                tvPhotoSelect = (TextView) window.findViewById(R.id.select_photo);
                tvPhotoSelect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
                        getAlbum.setType("image/*");
                        startActivityForResult(getAlbum, PHOTO_REQUEST_GALLERY);
                    }
                });
            }
            break;
    }
}

private void startPhotoZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    // crop為true是設定在開啟的intent中設定顯示的view可以剪裁
    intent.putExtra("crop", "true");

    // aspectX aspectY 是寬高的比例
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);

    // outputX,outputY 是剪裁圖片的寬高
    intent.putExtra("outputX", 300);
    intent.putExtra("outputY", 300);
    intent.putExtra("return-data", true);
    intent.putExtra("noFaceDetection", true);
    System.out.println("22================");
    startActivityForResult(intent, PHOTO_REQUEST_CUT);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case PHOTO_REQUEST_TAKEPHOTO:// 當選擇拍照時呼叫
            startPhotoZoom(Uri.fromFile(tempFile));
            break;
        case PHOTO_REQUEST_GALLERY:// 當選擇從本地獲取圖片時
            // 做非空判斷,當我們覺得不滿意想重新剪裁的時候便不會報異常,下同
            if (data != null) {
                System.out.println("11================");
                startPhotoZoom(data.getData());
            } else {
                System.out.println("================");
            }
            break;
        case PHOTO_REQUEST_CUT:// 返回的結果
            if (data != null)
                // setPicToView(data);
                sentPicToNext(data);
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void sentPicToNext(Intent data) {
    Bundle extras = data.getExtras();
    if (extras != null) {
        Bitmap photo = extras.getParcelable("data");
        photo = ImageUtils.scale(photo, 300, 300);
        FileOutputStream fout = null;
        imageSavePath = Constant.getImageCachePath(mContext);
        try {
            fout = new FileOutputStream(imageSavePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        photo.compress(mOutputFormat, 100, fout);
        upLoad();
        photo.recycle();
        try {
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 上傳圖片
 * create by weiang at 2016/5/20 17:33.
 */
private void upLoad() {
    File file = new File(imageSavePath);//filePath 圖片地址

    MultipartBody.Builder builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM);//
    RequestBody imageBody = RequestBody.create(MediaType.parse("image/jpg"), file);
    builder.addFormDataPart("pic", file.getName(), imageBody);//imgfile 後臺接收圖片流的引數名
    List<MultipartBody.Part> parts = builder.build().parts();
    Call<UploadAvatar> call = mApiService.uploadMemberIcon(parts);
    call.enqueue(new Callback<UploadAvatar>() {
        @Override
        public void onResponse(Call<UploadAvatar> call, final Response<UploadAvatar> response) {
            if (response.isSuccessful()) {
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hanleImageUpload(response.body());
                    }
                });
            }
        }

        @Override
        public void onFailure(Call<UploadAvatar> call, Throwable t) {

        }
    });
}

private void hanleImageUpload(UploadAvatar uploadAvatar) {
    if (uploadAvatar.getCode() == 0) {
        String path = uploadAvatar.getData();
        Glide.with(mContext)
                .load(path).
                transform(new GlideRoundTransform(mContext, 2))
                .into(personHomeIcon);
        mDialog.dismiss();
    } else {
        ToastUtils.showLongToast(uploadAvatar.getMessage());
        mDialog.dismiss();
    }


}