关闭

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

标签: 拍照上传头像
130人阅读 评论(0) 收藏 举报

一.从系统图库选择照片


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);
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1428次
    • 积分:94
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:0篇
    • 译文:0篇
    • 评论:5条
    文章分类
    文章存档
    最新评论