android 调用系统照相机拍照后剪裁

private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
private static final int PHOTO_REQUEST_CUT = 3;// 结果
/* 头像名称 */
private static String PHOTO_FILE_NAME = "temp_photo.jpg";
private Bitmap bitmap;
private File tempFile;
private String fileName = "temp.jpg";


1.点击事件

//头像
@Click(R.id.avatar_rl)
public void myinfo_iv(){
    Dialog dialog = new AlertDialog.Builder(this).setIcon(
            R.drawable.ic_launcher).setTitle("上传头像").setPositiveButton("相机拍照",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            "android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用,可用进行存储
                    if (Utils.hasSdcard()) {
                        SimpleDateFormat sDateFormat = new SimpleDateFormat(
                                "yyyyMMdd_HHmmss");
                        PHOTO_FILE_NAME = sDateFormat
                                .format(new java.util.Date()) + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                .fromFile(new File(Environment
                                        .getExternalStorageDirectory(),
                                        PHOTO_FILE_NAME)));
                    }
                    startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
                }
            }).setNegativeButton("手机相册", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent,
                    PHOTO_REQUEST_GALLERY);
        }
    }).create();
    dialog.show();
}

2.返回事件

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PHOTO_REQUEST_GALLERY) { //相册
        if (data != null) {
            // 得到图片的全路径
            Uri uri = data.getData();
            String DCIMPath = "";
            Cursor cr = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[] { MediaStore.Images.Media.DATA }, null, null,
                    MediaStore.Images.Media.DATE_MODIFIED + " desc");
            if (cr.moveToNext()) {
                DCIMPath = cr.getString(cr.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cr.close();
            if(uri!=null){
                fileName =getFileName(getRealPathFromURI(data.getData()));
                crop(uri);
            }else if(!TextUtils.isEmpty(DCIMPath)){
                fileName =getFileName(DCIMPath);
                crop(Uri.fromFile(new File(DCIMPath)));
            }else{
                Toast.makeText(MyinfoActivity.this, "未能获取到图片", Toast.LENGTH_SHORT).show();
            }
        }
    } else if (requestCode == PHOTO_REQUEST_CAMERA && resultCode != 0) {//拍照
        if (Utils.hasSdcard()) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);
            crop(Uri.fromFile(tempFile));
        } else {
            Toast.makeText(MyinfoActivity.this, "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show();
        }
    } else if (requestCode == PHOTO_REQUEST_CUT) {//结果
        if (data != null) {
            try {
                bitmap = data.getParcelableExtra("data");

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
                byte[] buffer = out.toByteArray();
                byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
                String photo = new String(encode);
                ACache mCache = ACache.get(this);
                String token = mCache.getAsString("token");
              WaitDialogUtil.showDialog(this);
                UpdatePicModel.updatepic(photo, token);

         /*       String userId = spUtil.getUserid();
                String verifyCode = spUtil.getkey();
                mDialog = DialogUtil.getLoginDialog(this);
                mDialog.show();
                RequestParams params = new RequestParams();
                params.put("ImagefileName", fileName);
                params.put("filestream", photo);
                params.put("userid", userId);
                params.put("verifyCode", verifyCode);
                String url = URLManage.FileUploadImage();*/
               /* HttpUtil.post(url, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          String responseBody, Throwable e) {
                        super.onFailure(statusCode, headers, responseBody,
                                e);
                        if (mDialog != null)
                            mDialog.dismiss();
                        if (statusCode == 0) {
                            T.showShort(getApplicationContext(),
                                    R.string.http_failure);
                        } else {
                            T.showShort(getApplicationContext(),
                                    R.string.server_failure);
                        }
                    }

                    @Override
                    public void onSuccess(JSONObject json) { // 返回的是JSONObject,会调用这里
                        L.i("json", json.toString());
                        if (mDialog != null)
                            mDialog.dismiss();
                        try {
                            int resultcode = json.getInt("resultcode");
                            if (resultcode == 0) {
                                imageLoader.displayImage(
                                        json.optString("data"), img_head,
                                        ImageUtil.getMyInfoHeadOptions());
                                spUtil.setHeadImg(json
                                        .optString("data"));
                                T.showShort(getApplicationContext(),
                                        "头像上传成功");
                            } else {
                                String msg = json.getString("msg");
                                T.showShort(getApplicationContext(), msg);
                            }
                        } catch (Exception e) {
                            L.e(e.toString());
                        }
                    };
                });*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
4.方法

/**
 * 从URI获取路径
 *
 * @param contentUri
 * @return
 */
public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

/**
 * 获取文件名+扩展名
 *
 * @param apath
 * @return
 */
public String getFileName(String apath) {
    int start = apath.lastIndexOf("/");
    int end = apath.length();
    // int end = apath.lastIndexOf(".");
    if (start != -1 && end != -1) {
        return apath.substring(start + 1, end);
    } else {
        return "temp.jpg";
    }
}
/**
 * 剪切图片
 *
 * @function:
 * @author:Jerry
 * @date:2013-12-30
 * @param uri
 */
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);// true:不返回uri,false:返回uri
    startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
5.上传服务器成功以后的处理

//更换头像
        EventCenter.bindContainerAndHandler(this, new BmSimpleEventHandler() {
            public void onEvent(UpdatePicEvent event) {
                myinfo_avatar.setImageBitmap(bitmap);
             WaitDialogUtil.dissMiss();
                ToastUtil.show(getApplicationContext(),"头像修改成功");
            }

        }).tryToRegisterIfNot();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值