1. 程式人生 > >安卓實現拍照、上傳圖片以及剪下圖片

安卓實現拍照、上傳圖片以及剪下圖片

效果圖:

總結一下專案實現的選擇圖片、拍照、以及剪下圖片,再加一下圖片壓縮,上傳到伺服器等功能

網上有好多關於圖片上傳、拍照的方法,我這只是自己專案的一種方式,之前部落格也是總結過圖集上傳,裡面也包含圖片上傳,拍照的相關程式碼,在這我單獨拿出來總結一下,還有關於呼叫系統的剪下功能,下面是點選彈出popuwindow顯示從相簿選擇還是拍照:

private void showPopupWindow() {
    View contentView = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow, null);
    View linearViewGroup = contentView.findViewById(R.id.linear_view_group);
    View tvCamera = contentView.findViewById(R.id.tv_pop_camera);
    View tvAlbum = contentView.findViewById(R.id.tv_pop_album);
    View tvCancle = contentView.findViewById(R.id.tv_pop_cancle);
    linearViewGroup.setOnClickListener(this);
    tvCamera.setOnClickListener(this);
    tvAlbum.setOnClickListener(this);
    tvCancle.setOnClickListener(this);
    mPopWnd = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    mPopWnd.showAtLocation(mRelativeParent, Gravity.BOTTOM, 0, 0);
    mPopWnd.setAnimationStyle(R.style.AnimBottom);
    mPopWnd.setOutsideTouchable(true);
    mPopWnd.setFocusable(false);
}
case R.id.tv_pop_camera://開啟系統相機
    mPopWnd.dismiss();
    if (Environment.getExternalStorageState().equals
            (android.os.Environment.MEDIA_MOUNTED)) {
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ContentValues values = new ContentValues();
        imageFilePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/YouJiao/xxt_teacher/pic/" + System.currentTimeMillis
                () + ".jpg";//設定圖片的儲存路徑
        File imageFile = new File(imageFilePath);//通過路徑建立儲存檔案
        imageUri = Uri.fromFile(imageFile);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, 1);
    } else {
        Toast.makeText(PersonalInfoActivity.this, "SD卡不存在,不能進行拍照功能..",
                Toast.LENGTH_SHORT).show();
    }
    break;
case R.id.tv_pop_album://開啟相簿
    mPopWnd.dismiss();
    Res.init(this);
    if (Bimp.tempSelectBitmap.size() > 0) {
        Bimp.tempSelectBitmap.clear();
    }
    PublicWay.num = 1;
    ImageSelectorUtils.openPhoto(this, 2, true, 0);
    break;
case R.id.tv_pop_cancle:
    mPopWnd.dismiss();
    break;
@Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {

    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case 1:
                Log.e("TAG", "***1");
                if (uritempFile != null) {
                    cropPhoto(uritempFile);
                }
                break;
            case 2:
                Log.e("TAG", "***2");
                ArrayList<String> images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
                cropPhoto(getUri(images.get(0)));// 裁剪圖片
                break;
            case 3:
                Log.e("TAG", "***3");
                if (data != null) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
                        upToServer(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
}
/**
 * 呼叫系統的裁剪功能
 *
 * @param uri
 */
public void cropPhoto(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");


    if (Environment.getExternalStorageState().equals
            (android.os.Environment.MEDIA_MOUNTED)) {
        imageFilePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/YouJiao/xxt_teacher/pic/" + System.currentTimeMillis
                () + ".jpg";//設定圖片的儲存路徑
        File imageFile = new File(imageFilePath);//通過路徑建立儲存檔案
        imageUri = Uri.fromFile(imageFile);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
    }
    intent.setDataAndType(uri, "image/*");
    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);


    /**
     * 此方法返回的圖片只能是小圖片(sumsang測試為高寬160px的圖片)
     * 故將圖片儲存在Uri中,呼叫時將Uri轉換為Bitmap,此方法還可解決miui系統不能return data的問題
     */
    //intent.putExtra("return-data", true);

    //uritempFile為Uri類變數,例項化uritempFile
    uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(intent, 3);
}

下面是上傳到伺服器程式碼:

  private void upToServer(final Bitmap bitmap) {
        String tempTime = System.currentTimeMillis() + "";
        File file = new File("/mnt/sdcard/" + tempTime + ".jpg");//將要儲存圖片的路徑
        try {
            BufferedOutputStream bos = null;
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            RequestParams params = new RequestParams(this);
            params.put("OP", "");//換成自己的op
            params.put("Member_ID", mStrUserId);
            OkHttpUtils.post()
                    .addFile("imgFile", "messenger_01.png", file)
                    .url(Constants.URL)//上傳的地址
                    .params(params)
                    .build()//
                    .execute(new StatusCallBack() {
                        @Override
                        public void onError(Request request, Exception e) {
                        }

                        @Override
                        public void onResponse(Status response) {
//                            mProgressDialog.dismiss();
                            SharedPreferences sharedPreferences = getSharedPreferences("text", Activity.MODE_PRIVATE);
                            //例項化SharedPreferences.Editor物件
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putInt("url", new Random().nextInt());
                            //提交當前資料
                            editor.apply();
                            if (response != null) {
                                if (response.getErrorCode().equals("200")) {
                                    SPUtils.setPrefString(getApplicationContext(), "headimgurl", response.getData());
                                    GlideUtils.loadHead(PersonalInfoActivity.this,
                                            response.getData(),
                                            mImgHead);
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }