[Android]抓取相簿圖片並且裁切

1.如果只需要抓取相簿圖片,不裁切的方法

onActivityResult加入
(android版本低於KITKAT使用selectImage(),以上的用getPath(), 網路查到的,功能可以正常執行,但未查明實際程序如何跑的)

            if (requestCode == IMAGE_TAKE && data != null) {
                userIconUri = data.getData();
                LogUtils.d(TAG, userIconUri.toString());
                userIconPath = selectImage(getActivity(), userIconUri);
//                userIconPath = getPath(getActivity(), userIconUri);
                LogUtils.d(TAG, userIconPath);
                ImageLoader.getInstance().displayImage(userIconPath, userIcon, mOptions);
                isImageChange = true;
            }
                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/jpeg");
                if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){
                    startActivityForResult(intent, IMAGE_TAKE_KITKAT);
                }else{
                    startActivityForResult(intent, IMAGE_TAKE);
                }

getPath()

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static boolean isNewGooglePhotoUri(Uri uri) {
        return "com.google.android.apps.photos.contentprovider".equals(uri.getAuthority());
    }

    public static String getImageUrlWithAuthority(Context context, Uri uri) {
        InputStream is = null;
        if (uri.getAuthority() != null) {
            LogUtils.d(TAG, "getImageUrlWithAuthority");
            try {
                is = context.getContentResolver().openInputStream(uri);
                Bitmap bmp = BitmapFactory.decodeStream(is);
                return writeToTempImageAndGetPathUri(context, bmp).toString();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

selectImage()

    public static String selectImage(Context context,Uri data){
        Uri selectedImage = data;
//      Log.e(TAG, selectedImage.toString());
        if(selectedImage!=null){
            String uriStr=selectedImage.toString();
            String path=uriStr.substring(10,uriStr.length());
            if(path.startsWith("com.sec.android.gallery3d")){
                LogUtils.e(TAG, "It's auto backup pic path:"+selectedImage.toString());
                return null;
            }
        }
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }

我原本使用的方法

    private String getPathFromURI(Uri selectedImage) {
        final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
        Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        String filePath = "";
        // some devices (OS versions return an URI of com.android instead of com.google.android
        if (selectedImage.toString().startsWith("content://com.android.gallery3d.provider"))  {
            // use the com.google provider, not the com.android provider.
            selectedImage = Uri.parse(selectedImage.toString().replace("com.android.gallery3d","com.google.android.gallery3d"));
            filePath = selectedImage.getPath();
        } else if (selectedImage.toString().startsWith("content://com.google.android.apps.photos.content/"))  {
            // use the com.google provider, not the com.android provider.
            filePath = selectedImage.getLastPathSegment();
        } else if (selectedImage.toString().startsWith("content://com.google.android.apps.photos.contentprovider"))  {
            // use the com.google provider, not the com.android provider.
            filePath = getImageUrlWithAuthority(getActivity(), selectedImage);
        } else {
            filePath = Uri.decode(userIconUri.toString());
        }
        return filePath;
    }

    public static String getImageUrlWithAuthority(Context context, Uri uri) {
        InputStream is = null;
        if (uri.getAuthority() != null) {
            LogUtils.d(TAG, "getImageUrlWithAuthority");
            try {
                is = context.getContentResolver().openInputStream(uri);
                Bitmap bmp = BitmapFactory.decodeStream(is);
                return writeToTempImageAndGetPathUri(context, bmp).toString();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static Uri writeToTempImageAndGetPathUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

上面的程式執行完,會發現圖片可能會有翻轉角度不正常的,還需要另外判斷角度的數據
(這是網路上查到的資料,還未執行過,等以後要使用再來了解程序如何執行的)

    public static int getExifOrientation(String filepath) {// YOUR MEDIA PATH AS STRING
        int degree = 0;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if (exif != null) {
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            if (orientation != -1) {
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }

            }
        }
        return degree;
    }

2.抓取相簿圖片,並裁切的方法
先執行Intent.ACTION_GET_CONTENT去圖庫抓圖,返回時再Intent com.android.camera.action.CROP 裁切圖片

                Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, RESULT_LOAD_IMAGE);

onActivityResult()

            if (requestCode == RESULT_LOAD_IMAGE) {
                final String CROP_ACTION = "com.android.camera.action.CROP";
                Intent photoCropIntent = new Intent(CROP_ACTION);
                photoCropIntent.putExtra("crop", "true");
                photoCropIntent.putExtra("aspectX", 1);
                photoCropIntent.putExtra("aspectY", 1);
                photoCropIntent.putExtra("outputX", 300);
                photoCropIntent.putExtra("outputY", 300);
                photoCropIntent.putExtra("scale", true);
                photoCropIntent.putExtra("return-data", false);
                photoCropIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(getActivity()));
                photoCropIntent.putExtra("outputFormat",
                        Bitmap.CompressFormat.JPEG.toString());
                photoCropIntent.setDataAndType(data.getData(), "image/*");

                startActivityForResult(photoCropIntent, RESULT_CROP_IMAGE);
            }

            if (requestCode == RESULT_CROP_IMAGE) {
                String uriString = null;
                if (data.getAction() != null) {
                    LogUtils.d(TAG, "action");
                    uriString = data.getAction();
                } else if (data.getData() != null) {
                    LogUtils.d(TAG, "data");
                    uriString = data.getDataString();
                }
                LogUtils.d(TAG, "userIconPath:" + uriString);
                if (uriString.startsWith("/")) {
                    ImageLoader.getInstance().displayImage("file://" + uriString, userIcon, mOptions);
                } else {
                    ImageLoader.getInstance().displayImage(uriString, userIcon, mOptions);
                }
            }

建立一個Uri給裁切的圖片使用(Uri如同一個檔案位置)

    private static Uri getTempUri(Context context) {
        return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
    }

參考網址:
http://my.oschina.net/ryanhoo/blog/86853
http://my.oschina.net/ryanhoo/blog/86842
http://androidbiancheng.blogspot.tw/2011/01/extraoutput.html
http://www.eoeandroid.com/home.php?mod=space&uid=1289462&do=blog&id=49568
http://stackoverflow.com/questions/23236392/failure-delivering-resultinfo

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *