安卓实现拍照、上传图片以及剪切图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoshuxgh/article/details/85161496

效果图:

总结一下项目实现的选择图片、拍照、以及剪切图片,再加一下图片压缩,上传到服务器等功能

网上有好多关于图片上传、拍照的方法,我这只是自己项目的一种方式,之前博客也是总结过图集上传,里面也包含图片上传,拍照的相关代码,在这我单独拿出来总结一下,还有关于调用系统的剪切功能,下面是点击弹出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();
        }
    }

猜你喜欢

转载自blog.csdn.net/xiaoshuxgh/article/details/85161496