Android SDK4/5/6/7,相册、拍照及裁剪功能及遇见的坑

保存照片和视频到系统相册显示- http://blog.csdn.net/chendong_/article/details/52290329

Android 7.0 之拍照与图片裁剪适配-http://blog.csdn.net/yyh352091626/article/details/54908624

拍照、相册及裁剪的终极实现(一)——拍照及裁剪功能实现- http://blog.csdn.net/harvic880925/article/details/43163175

看似简单的问题,在各个厂商手机上有不同的问题,请广而测之,

> 方案如下:将中间数据先暂存一下,然后再调裁剪Intent,最后把结果存在Uri中。
//打开相册
public void openAlbum() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, PHOTO_REQUEST_ALBUM);
    }

    private File mPhotoFile;
//打开相机
    private void openCamera(File out) {
        LogUtil.e("openCamera", "mPhotoFile=" + mPhotoFile.toString());
// Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out)); // set
// intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showLongToast(mContext,"当前无拍照权限,请在 设置-> 应用权限-> "+ mContext.getString(R.string.app_name)+"-> 权限-> 打开相机权限","");
        } finally {
        }
    }

private int PHOTO_REQUEST_CAREMA = 1001;// 拍照
private int PHOTO_REQUEST_ALBUM = 1002;// 从相册中选择
private int PHOTO_REQUEST_CUT = 1003;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

 

 super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("onActivityResult","exe onActivityResult()");
        String picPath = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == PHOTO_REQUEST_ALBUM) {// 相册
Uri selectedImage = data.getData();
                if (data != null) {
                    Uri uri = data.getData();
                    crop(uri);
                    filePath = getRealPathFromURI(uri);
                    LogUtils.e("onActivityResult","filePath="+filePath);
                }
                LogUtil.e("onActivityResult", "相册 picPath= empty");
            } else if (requestCode == PHOTO_REQUEST_CAREMA) {// 拍照
if (mPhotoFile != null && mPhotoFile.exists()) {
                    crop(Uri.fromFile(mPhotoFile));
                    filePath = mPhotoFile.toString();
                    LogUtils.e("onActivityResult","filePath="+filePath);
                }
            } else if (requestCode == PHOTO_REQUEST_CUT) {
                Uri uri = data.getData();
                LogUtils.e("PHOTO_REQUEST_CUT", "uri=" + uri);
                if (uri != null) {
                    if (uri.toString().contains("content://")) { //如果包含有content开头,需要转化为其实际路径,不能用content开头
filePath = getRealPathFromURI(uri);
                    } else {
                        filePath = uri.toString();       //如果用file开头,不用转化
}
                    LogUtils.e("PHOTO_REQUEST_CUT", "filePath=" + filePath);
                    uploadAvatar();
                } else {
                    uploadAvatar();
//                    ToastUtil.showShortToast(NyApplication.getInstance(), R.string.dataError);
}
            } 

        }

 

}

 

//裁剪图

 

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(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", false);// true:不返回uri,false:返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    /**
     * 传入Uri,得到图片的真实路径
     *
     * @param contentUri
     * @return
     */
    private String getRealPathFromURI(Uri contentUri) { //传入图片uri地址
        String picPath = null;
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        cursor = mContext.getContentResolver().query(contentUri,
                filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor
                    .getColumnIndex(filePathColumn[0]);
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }
        return picPath;
    }

Htc提示SD卡已满 Android -- https://zhidao.baidu.com/question/1048799384918824739.html

     https://zhidao.baidu.com/question/2202745883929714388.html

 

public String getRealFilePath( final Context context, final Uri uri ) {
    if ( null == uri ) return null;
    final String scheme = uri.getScheme();
    String data = null;
    if ( scheme == null )
        data = uri.getPath();
    else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
        data = uri.getPath();
    } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
        Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
        if ( null != cursor ) {
            if ( cursor.moveToFirst() ) {
                int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                if ( index > -1 ) {
                    data = cursor.getString( index );
                }
            }
            cursor.close();
        }
    }
    return data;
}
/**
 * 根据图片FileUrl路径获取ContentUri
 *
 * @param
* @param
* @return
*/
public Uri convertFileToUri(Context context, File imageFile) {
    String filePath = imageFile.getAbsolutePath();
    Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Images.Media._ID},
            MediaStore.Images.Media.DATA + "=? ",
            new String[]{filePath}, null);

    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor
                .getColumnIndex(MediaStore.MediaColumns._ID));
        Uri baseUri = Uri.parse("content://media/external/images/media");
        return Uri.withAppendedPath(baseUri, "" + id);
    } else {
        if (imageFile.exists()) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            return context.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
}

     图片路径URL与URI的相互转化???

 

>>> Android7.0 拍照及裁剪的坑

 Android7.0适配心得-- http://www.tuicool.com/articles/zYniuyZ   ,   http://stackoverflow.com/questions/7305504/convert-file-uri-to-content-uri
  

> error:No such file or directory,java.io.UnixFileSystem.createFileExclusively0,文件夹目录需要先创建,然后再在相应的文件夹目录下创建文件
File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
    f.getParentFile().mkdirs();//创建文件夹
if (!f.exists())
    f.createNewFile();//创建文件

 

--------------------------------------------------

 

File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File dir = new File(appDir, formatCurrentDate("yyyy_MM_dd_HH_mm_ss") + ".jpg");
//        dir.delete();
//        if (!dir.exists()) {
//            try {
//                dir.createNewFile();
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            LogUtils.e("CommonUtils", "success createFile dir=" + dir.toString());
//            return dir;
//        } else {
//            LogUtils.e("CommonUtils", "success createFile dir=" + dir.toString());
//            return dir;
//        }
if (!dir.exists()) {
            try {
                if (!dir.getParentFile().exists()){
                    dir.getParentFile().mkdirs();
                }
                if (!dir.exists()){
                    dir.createNewFile();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtils.e("CommonUtils", "success createFile dir=" + dir.toString());
            return dir;
        } else {
            LogUtils.e("CommonUtils", "success createFile dir=" + dir.toString());
            return dir;
        }
posted @ 2018-02-06 01:18  牧之丨  阅读(463)  评论(0编辑  收藏  举报