获取照片的uri

获取照片的uri

增加第三方的动态申请权限EasyPermissions gitHub上的库

/**
 * 开启相机
 */
@AfterPermissionGranted(RC_CAMERA_PERM)
public void openCamera() {
    String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    if (EasyPermissions.hasPermissions(this, perms)) {
        // Have permission, do the thing!
        open();
        // Toast.makeText(this, "TODO: WRITE_EXTERNAL", Toast.LENGTH_LONG).show();

    } else {
        // Ask for one permission
        EasyPermissions.requestPermissions(this, getString(R.string.write_external),
                RC_CAMERA_PERM, perms);
    }
}

String path = Environment.getExternalStorageDirectory().toString() + "/picture";

/**
 * 打开系统相机
 */
private void open() {

    // TODO: 2017/5/10
    if (AppUtil.isExitsSdcard()) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        capturePath = path + "/" + System.currentTimeMillis() + ".jpg";
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePath)));
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, RC_CAMERA_PERM);
    }

}


/**
 * 从相册选择
 */
private void selectFromAlbum() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
    startActivityForResult(intent, RC_REQUEST_PICK_IMAGE);
}


/**
 * 从相册选择
 */
@AfterPermissionGranted(RC_REQUEST_PICK_IMAGE)
public void openPicture() {
    if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // Have permission, do the thing!
        selectFromAlbum();
        // Toast.makeText(this, "TODO: WRITE_EXTERNAL", Toast.LENGTH_LONG).show();

    } else {
        // Ask for one permission
        EasyPermissions.requestPermissions(this, getString(R.string.write_external),
                RC_REQUEST_PICK_IMAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
}

//权限
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
    Log.e(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
}

@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
    Log.e(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

    // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
    // This will display a dialog directing them to enable the permission in app settings.
    if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
        new AppSettingsDialog.Builder(this).build().show();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
        // Do something after user returned from app settings screen, like showing a Toast.
        //            Toast.makeText(this, "returned_from_app_settings_to_activity", Toast.LENGTH_SHORT).show();
    }

    switch (requestCode) {
        //从系统选择图片
        case RC_REQUEST_PICK_IMAGE:
            if (Build.VERSION.SDK_INT >= 19) {
                handleImageOnKitKat(data, RC_REQUEST_PICK_IMAGE);
            } else {
                handleImageBeforeKitKat(data, RC_REQUEST_PICK_IMAGE);
            }
            break;
        //裁剪图片
        case RC_REQUEST_PICTURE_CUT:
            if (data != null) {

                String imgCode = null;
                try {
                    imgCode = encodeBase64File(imagePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LogUtil.e("相册 上传图片");
                //上传图片
                updateImg(imgCode);
            }
            break;
        //拍照
        case RC_CAMERA_PERM:
            LogUtil.e("RC_CAMERA_PERM");
            if (resultCode == Activity.RESULT_OK) {
                Uri uri = Uri.fromFile(new File(capturePath));
                LogUtil.e("路径===" + uri.getPath());
                if (uri != null) {
                    //裁剪图片
                    cropSavePhoto(uri, RC_CAMERA_PERM);
                }
            }
            break;
        //拍照后裁剪
        case RC_REQUEST_CAMERA_PICTURE_CUT:
            if (data != null) {
                String cameraCode = null;
                try {
                    cameraCode = encodeBase64File(capturePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                updateImg(cameraCode);
            }
            break;
    }


}


@TargetApi(19)
private void handleImageOnKitKat(Intent data, int code) {
    if (data != null) {
        imagePath = null;
        Uri data1 = data.getData();
        if (data1 != null) {
            imagePath = returnPath(data1);
            //裁剪照片
            cropSavePhoto(data1, code);
        }
    }

}

private void handleImageBeforeKitKat(Intent data, int code) {
    if (data != null) {
        Uri data2 = data.getData();
        if (data2 != null) {
            imagePath = getImagePath(data2, null);
            //裁剪照片
            cropSavePhoto(data2, code);

        }
    }


}

/**
 * 返回照片的uri
 *
 * @param uri
 * @return
 */
private String returnPath(Uri uri) {
    String path = null;
    if (DocumentsContract.isDocumentUri(this, uri)) {
        //如果是document类型的uri,则通过document id处理
        String docId = DocumentsContract.getDocumentId(uri);
        if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
            String id = docId.split(":")[1];//解析出数字格式的id
            String selection = MediaStore.Images.Media._ID + "=" + id;
            path = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
        } else if ("com.android.downloads.documents".equals(uri.getAuthority())) {
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
            path = getImagePath(contentUri, null);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        //如果是content类型的Uri,则使用普通方式处理
        path = getImagePath(uri, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        //如果是file类型的Uri,直接获取图片路径即可
        path = uri.getPath();
    }
    return path;
}

private String getImagePath(Uri uri, String selection) {
    String path = null;
    //通过Uri和selection老获取真实的图片路径
    Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        }
        cursor.close();
    }
    return path;
}


/**
 * 裁剪图片
 *
 * @param uri
 */
private void cropSavePhoto(Uri uri, int code) {

    try {
        String fromURI = null;
        if (code == RC_REQUEST_PICK_IMAGE) {
            //从相册获取
            fromURI = getRealPathFromURI(uri);
        } else if (code == RC_CAMERA_PERM) {
            //拍照获取
            fromURI = uri.getPath();
        }

        //1.加载位图
        FileInputStream is = new FileInputStream(fromURI);
        //2.为位图设置100K的缓存
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTempStorage = new byte[100 * 1024];
        //3.设置位图颜色显示优化方式
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        //4.设置图片可以被回收
        opts.inPurgeable = true;
        //5.设置位图缩放比例
        opts.inSampleSize = 4;
        //6.设置解码位图的尺寸信息
        opts.inInputShareable = true;
        //7.解码位图
        Bitmap btp = BitmapFactory.decodeStream(is, null, opts);
        //8.显示位图
        // preview.setImageBitmap(bitmap);

        //把file转换成bitmap后,获得高宽
        if (btp != null) {
            int width = btp.getWidth();
            int height = btp.getHeight();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("outputX", width);
            intent.putExtra("outputY", height);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);

            switch (code) {
                case RC_REQUEST_PICK_IMAGE:
                    startActivityForResult(intent, RC_REQUEST_PICTURE_CUT);
                    break;
                case RC_CAMERA_PERM:
                    LogUtil.e("拍照后");
                    startActivityForResult(intent, RC_REQUEST_CAMERA_PICTURE_CUT);
                    break;
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * 根据Uri获取图片路径
 *
 * @param contentUri
 * @return
 */
public String getRealPathFromURI(Uri contentUri) {
    String res = null;
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
    }

    return res;
}


/**
 * 上传图片
 *
 * @param imgCode
 */
private void updateImg(String imgCode) {
    BaseHttpRequest<String> request = new BaseHttpRequest<String>(mActivity) {
        @Override
        protected SubjectPostApi request() {
            return new SubjectPostApi(SubjectPostApi.UPLOAD_TYPE_IMG).uploadImg(mParams);
        }

        @Override
        public void onNext(String resulte, String method) {
            LogUtil.e("上传图片", resulte);
            try {
                JSONObject object = new JSONObject(resulte);
                if (object.has("resCode")) {
                    int code = object.getInt("resCode");
                    if (code == 0) {
                        if (object.has("data")) {
                            String picUrl = object.getString("data");
                            createMessage(picUrl);
                            LogUtil.e(picUrl);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onError(ApiException e) {
            LogUtil.e("上传图片", "错误" + e);
            ToastUtil.showSafeToast("请检查网络");
        }
    };
    request.addParams("pic", imgCode);
    request.requestBack();
}

private void cropSavePhoto(Uri uri, int code) {
try {
String fromURI = null;
if (code == RC_REQUEST_PICK_IMAGE) {
//从相册获取
fromURI = getRealPathFromURI(uri);
} else if (code == RC_CAMERA_PERM) {
//拍照获取
fromURI = uri.getPath();
}
LogUtil.e(“path==” + fromURI);
//1.加载位图
FileInputStream is = new FileInputStream(fromURI);
//2.为位图设置100K的缓存
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inTempStorage = new byte[100 * 1024];
//3.设置位图颜色显示优化方式
opts.inPreferredConfig = Bitmap.Config.RGB_565;
//4.设置图片可以被回收
opts.inPurgeable = true;
//5.设置位图缩放比例
opts.inSampleSize = 4;
//6.设置解码位图的尺寸信息
opts.inInputShareable = true;

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        is.close();

        byte[] data = outStream.toByteArray();

        //7.解码位图
        if (data != null) {
            Bitmap btp = BitmapFactory.decodeByteArray(data, 0, data.length);
            //把file转换成bitmap后,获得高宽
            if (btp != null) {
                int width = btp.getWidth();
                int height = btp.getHeight();
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(uri, "image/*");
                intent.putExtra("crop", "true");
                intent.putExtra("outputX", width);
                intent.putExtra("outputY", height);
                intent.putExtra("scale", true);
                intent.putExtra("return-data", false);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                intent.putExtra("noFaceDetection", true);

                switch (code) {
                    case RC_REQUEST_PICK_IMAGE:
                        LogUtil.e("调用相册");
                        startActivityForResult(intent, RC_REQUEST_PICTURE_CUT);
                        break;
                    case RC_CAMERA_PERM:
                        LogUtil.e("拍照后");
                        startActivityForResult(intent, RC_REQUEST_CAMERA_PICTURE_CUT);
                        break;
                }

            }
        }

        //8.显示位图
        // preview.setImageBitmap(bitmap);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值