两分钟搞定从图库或者拍照上传头像~

一.从系统图库选择照片


1、跳转系统图库

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, Constant.IMAGE_REQUEST_CODE);
2、获取图片地址

@Override
protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
        case Constant.IMAGE_REQUEST_CODE:
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    SnackBarUtil.show(mContext, "获取图片失败");
                    return;
                }
                showProgressDialog("正在上传");
                String uriToImagePath = FileUtils.UriToImagePath(data.getData(), mContext);
                if (!TextUtils.isEmpty(uriToImagePath)) {
                    //do Something
                }


            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

public static String UriToImagePath(Uri uri, Context context) {
    String imageUpPath = "";
    if (!TextUtils.isEmpty(uri.getAuthority())) {
        Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
        if (cursor == null) {
            return null;
        } else {
            cursor.moveToFirst();
            imageUpPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            cursor.close();
        }

    } else {
        imageUpPath = uri.getPath();
    }
    return imageUpPath;
}

二.拍照选择照片

1、调用系统相机

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
captureImgPath = new File(FileUtil.getDirectory(Constant.cachePath), DateUtil.getNowString(DateUtil.DATETIMESTR) + ".jpg")
        .getAbsolutePath();//保存拍的照片~
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(captureImgPath)));
startActivityForResult(intent, Constant.CAMERA_REQUEST_CODE);
2、获取图片地址

@Override
protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
 
        case Constant.CAMERA_REQUEST_CODE:
            if (resultCode == RESULT_OK && !TextUtils.isEmpty(captureImgPath)) {
           	 //doSomething
            }
            break;
      
    }
    super.onActivityResult(requestCode, resultCode, data);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值