1. 程式人生 > >呼叫系統照相機和相簿

呼叫系統照相機和相簿

介紹的文章很多,這裡通過一個例項來展示,先看看選項:一個顯示頭像的ImageView和點選後彈出的選項框(選項框的製作在之前的文章有介紹http://blog.csdn.net/nzzl54/article/details/52086007)


接下來是看看結構:


一個一個檔案講解:

1.AdvancedFileUtils:高階的檔案處理工具

public class AdvancedFileUtils {
	public static File getDiskCacheDir(Context context, String uniqueName) {
		// Check if media is mounted or storage is built-in, if so, try and use
		// external cache dir
		// otherwise use internal cache dir

		final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState()) || !isExternalStorageRemovable() ? getExternalCacheDir(
				context).getPath()
				: context.getCacheDir().getPath();

		return new File(cachePath + File.separator + uniqueName);
	}
	/**
	 * Check if external storage is built-in or removable.
	 *
	 * @return True if external storage is removable (like an SD card), false
	 *         otherwise.
	 */
	@TargetApi(9)
	public static boolean isExternalStorageRemovable() {
		if (Build.VERSION.SDK_INT >= 9) {
			return Environment.isExternalStorageRemovable();
		}
		return true;
	}

	/**
	 * Get the external app cache directory.
	 *
	 * @param context
	 *            The context to use
	 * @return The external cache dir
	 */
	private static File getExternalCacheDir(Context context) {
		// if (BaseVersionUtils.hasFroyo()) {
		// return context.getExternalCacheDir();
		// }

		// Before Froyo we need to construct the external cache dir ourselves
		final String cacheDir = "/Android/data/" + context.getPackageName()
				+ "/cache/";


		return new File(Environment.getExternalStorageDirectory().getPath()
				+ cacheDir);
	}
	/**
	 * 獲取副檔名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileFormat(String fileName) {
		if (StringUtils.isEmpty(fileName))
			return "";

		int point = fileName.lastIndexOf('.');
		return fileName.substring(point + 1);
	}

	/**
	 * 根據檔案絕對路徑獲取檔名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileName(String filePath) {
		if (StringUtils.isEmpty(filePath))
			return "";
		return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
	}
	/**
	 * 
	 * @param path 檔案路徑
	 * @param fileName 檔名,如xxx.jpg
	 * @param b
	 * @return 返回儲存本地成功與否
	 */
	public static boolean saveBitmapToLocal(String path,String fileName,Bitmap b){
		if (b == null) {
			return false;
		}
		
		boolean result = false ;
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileOutputStream fos=null;
			
			try {
				fos = new FileOutputStream(path + fileName);
				b.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				result = true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
								
		}	
		return result;
	}

}

2.BottomSelectorPopDialog:自定義彈框,略

3.Helper_Image:這裡暫時不用,略

4.ImageUtils:工具類-圖片處理

public class ImageUtils {
    public final static String SDCARD_MNT = "/mnt/sdcard";
    //	public final static String SDCARD = "/sdcard";
    public final static String SDCARD = Environment.getExternalStorageDirectory().getPath();
    // 請求相簿
    public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
    //請求相機
    public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
    //請求裁剪
    public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;

    /**
     * 寫圖片檔案 在Android系統中,檔案儲存在 /data/data/PACKAGE_NAME/files 目錄下
     *
     * @throws IOException
     */
    public static void saveImage(Context context, String fileName, Bitmap bitmap)
            throws IOException {
        saveImage(context, fileName, bitmap, 100);
    }

    public static void saveImage(Context context, String fileName,
                                 Bitmap bitmap, int quality) throws IOException {
        if (bitmap == null || fileName == null || context == null)
            return;

        FileOutputStream fos = context.openFileOutput(fileName,
                Context.MODE_PRIVATE);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
        byte[] bytes = stream.toByteArray();
        fos.write(bytes);
        fos.close();
    }

    /**
     * 寫圖片檔案到SD卡
     *
     * @throws IOException
     */
    public static void saveImageToSD(Context ctx, String filePath,
                                     Bitmap bitmap, int quality) throws IOException {
        if (bitmap != null) {
            File file = new File(filePath.substring(0,
                    filePath.lastIndexOf(File.separator)));
            if (!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(filePath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
            if(ctx!=null){
                scanPhoto(ctx, filePath);
            }
        }
    }

    public static void saveBackgroundImage(Context ctx, String filePath, Bitmap bitmap, int quality) throws IOException{
        if (bitmap != null) {
            File file = new File(filePath.substring(0,
                    filePath.lastIndexOf(File.separator)));
            if (!file.exists()) {
                file.mkdirs();
            }
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(filePath));
            bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos);
            bos.flush();
            bos.close();
            if(ctx!=null){
                scanPhoto(ctx, filePath);
            }
        }
    }


    /**
     * 讓Gallery上能馬上看到該圖片
     */
    private static void scanPhoto(Context ctx, String imgFileName) {
        Intent mediaScanIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File(imgFileName);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        ctx.sendBroadcast(mediaScanIntent);
    }

    /**
     * 獲取bitmap
     *
     * @param context
     * @param fileName
     * @return
     */
    public static Bitmap getBitmap(Context context, String fileName) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = context.openFileInput(fileName);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return bitmap;
    }

    /**
     * 獲取bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmapByPath(String filePath) {
        return getBitmapByPath(filePath, null);
    }

    public static Bitmap getBitmapByPath(String filePath,
                                         BitmapFactory.Options opts) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }

        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(fis, null, opts);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return bitmap;
    }

    /**
     * 網路地址轉換為bitmap
     * @param url
     * @return
     */
    public static Bitmap returnBitMap(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try
        {
            in = new BufferedInputStream(new URL(url).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
    /**
     * 獲取bitmap
     *
     * @param file
     * @return
     */
    public static Bitmap getBitmapByFile(File file) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return bitmap;
    }


    /**
     * 使用當前時間戳拼接一個唯一的檔名
     * @return
     */
    public static String getTempFileName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS", Locale.CHINA);
        String fileName = format.format(new Timestamp(System
                .currentTimeMillis()));
        return fileName;
    }

    /**
     * 獲取照相機使用的目錄
     *
     * @return
     */
    public static String getCamerPath() {
        return Environment.getExternalStorageDirectory() + File.separator
                + "FounderNews" + File.separator;
    }


    /**
     * 判斷當前Url是否標準的content://樣式,如果不是,則返回絕對路徑
     *
     * @param mUri
     * @return
     */
    public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
        String filePath = null;

        String mUriString = mUri.toString();
        mUriString = Uri.decode(mUriString);

        String pre1 = "file://" + SDCARD + File.separator;
        String pre2 = "file://" + SDCARD_MNT + File.separator;

        if (mUriString.startsWith(pre1)) {
            filePath = Environment.getExternalStorageDirectory().getPath()
                    + File.separator + mUriString.substring(pre1.length());
        } else if (mUriString.startsWith(pre2)) {
            filePath = Environment.getExternalStorageDirectory().getPath()
                    + File.separator + mUriString.substring(pre2.length());
        }
        return filePath;
    }

    /**
     * 通過uri獲取檔案的絕對路徑
     *
     * @param uri
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String getAbsoluteImagePath(Activity context, Uri uri) {
        String imagePath = "";
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.managedQuery(uri, proj, // Which columns to
                // return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)

        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                imagePath = cursor.getString(column_index);
            }
        }

        return imagePath;
    }


    public static Bitmap loadImgThumbnail(String filePath, int w, int h) {
        Bitmap bitmap = getBitmapByPath(filePath);
        if (bitmap!=null) {
            return zoomBitmap(bitmap, w, h);
        }else {
            return bitmap;
        }
    }

    public static Bitmap loadDefaultImg(Bitmap bm,int w,int h){
        return zoomBitmap(bm, w, h);
    }


    /**
     * 計算縮放圖片的寬高
     *
     * @param img_size
     * @param square_size
     * @return
     */
    public static int[] scaleImageSize(int[] img_size, int square_size) {
        if (img_size[0] <= square_size && img_size[1] <= square_size)
            return img_size;
        double ratio = square_size
                / (double) Math.max(img_size[0], img_size[1]);
        return new int[] { (int) (img_size[0] * ratio),
                (int) (img_size[1] * ratio) };
    }
    /**
     * 建立縮圖
     *
     * @param context
     * @param largeImagePath
     *            原始大圖路徑
     * @param thumbfilePath
     *            輸出縮圖路徑
     * @param square_size
     *            輸出圖片寬度
     * @param quality
     *            輸出圖片質量
     * @throws IOException
     */
    public static void createImageThumbnail(Context context,
                                            String largeImagePath, String thumbfilePath, int square_size,
                                            int quality) throws IOException {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 1;
        // 原始圖片bitmap
        Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);

        if (cur_bitmap == null)
            return;

        // 原始圖片的高寬
        int[] cur_img_size = new int[] { cur_bitmap.getWidth(),
                cur_bitmap.getHeight() };
        // 計算原始圖片縮放後的寬高
        int[] new_img_size = scaleImageSize(cur_img_size, square_size);
        // 生成縮放後的bitmap
        Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0],
                new_img_size[1]);
        // 生成縮放後的圖片檔案
        saveImageToSD(null,thumbfilePath, thb_bitmap, quality);
    }

    /**
     * 放大縮小圖片
     *
     * @param bgimage
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap zoomBitmap(Bitmap bgimage, double newWidth, double newHeight) {

        // 獲取這個圖片的寬和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 建立操作圖片用的matrix物件
        Matrix matrix = new Matrix();
        // 計算寬高縮放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 縮放圖片動作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    public static Bitmap scaleBitmap(Bitmap bitmap) {
        // 獲取這個圖片的寬和高
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 定義預轉換成的圖片的寬度和高度
        int newWidth = 200;
        int newHeight = 200;
        // 計算縮放率,新尺寸除原始尺寸
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 建立操作圖片用的matrix物件
        Matrix matrix = new Matrix();
        // 縮放圖片動作
        matrix.postScale(scaleWidth, scaleHeight);
        // 旋轉圖片 動作
        // matrix.postRotate(45);
        // 建立新的圖片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return resizedBitmap;
    }



    /**
     * (縮放)重繪圖片
     *
     * @param context
     *            Activity
     * @param bitmap
     * @return
     */
    public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
//		int rHeight = dm.heightPixels;
        int rWidth = dm.widthPixels;
//		int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        float zoomScale;

        if (width >= rWidth)
            zoomScale = ((float) rWidth) / width;
        else
            zoomScale = 1.0f;
        // 建立操作圖片用的matrix物件
        Matrix matrix = new Matrix();
        // 縮放圖片動作
        matrix.postScale(zoomScale, zoomScale);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    /**
     * 將Drawable轉化為Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
                .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;

    }

    /**
     * 獲得圓角圖片的方法
     *
     * @param bitmap
     * @param roundPx
     *            一般設成14
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 獲得帶倒影的圖片方法
     *
     * @param bitmap
     * @return
     */
    public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
        final int reflectionGap = 4;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);

        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
                width, height / 2, matrix, false);

        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                (height + height / 2), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint deafalutPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);

        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
                bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
                0x00ffffff, Shader.TileMode.CLAMP);
        paint.setShader(shader);
        // Set the Transfer mode to be porter duff and destination in
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        // Draw a rectangle using the paint with our linear gradient
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                + reflectionGap, paint);

        return bitmapWithReflection;
    }

    /**
     * 獲取圖片型別
     *
     * @param file
     * @return
     */
    public static String getImageType(File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            String type = getImageType(in);
            return type;
        } catch (IOException e) {
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 獲取圖片的型別資訊
     *
     * @param in
     * @return
     * @see #getImageType(byte[])
     */
    public static String getImageType(InputStream in) {
        if (in == null) {
            return null;
        }
        try {
            byte[] bytes = new byte[8];
            in.read(bytes);
            return getImageType(bytes);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 獲取圖片的型別資訊
     *
     * @param bytes
     *            2~8 byte at beginning of the image file
     * @return image mimetype or null if the file is not image
     */
    public static String getImageType(byte[] bytes) {
        if (isJPEG(bytes)) {
            return "image/jpeg";
        }
        if (isGIF(bytes)) {
            return "image/gif";
        }
        if (isPNG(bytes)) {
            return "image/png";
        }
        if (isBMP(bytes)) {
            return "application/x-bmp";
        }
        return null;
    }

    private static boolean isJPEG(byte[] b) {
        if (b.length < 2) {
            return false;
        }
        return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
    }

    private static boolean isGIF(byte[] b) {
        if (b.length < 6) {
            return false;
        }
        return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8'
                && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
    }

    private static boolean isPNG(byte[] b) {
        if (b.length < 8) {
            return false;
        }
        return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78
                && b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10
                && b[6] == (byte) 26 && b[7] == (byte) 10);
    }

    private static boolean isBMP(byte[] b) {
        if (b.length < 2) {
            return false;
        }
        return (b[0] == 0x42) && (b[1] == 0x4d);
    }

    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * 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;
    }

<pre name="code" class="java">     /**
     * @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());
    }
}
5.PhotoOperation:獲取圖片截圖的方法
public class PhotoOperation {

    /**
     * 根據Uri得到真實路徑
     *
     * @param context 上下文
     * @param uri     絕對路徑
     * @return 真實路徑
     */
    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;
    }

    public static Uri cropUri;  //需要裁剪的Uri
    private Context mContext;

    /**
     * 裁剪頭像的絕對路徑
     */
    public Uri getUploadTempFile(Context context, Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(StringUtils.IMAGE_SAVE_PATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
//            T.showShort(this, "無法儲存上傳的頭像,請檢查SD卡是否掛載");
            //彈出提示
//            Toast.Long(context, R.string.text_save_photo_failed);
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是標準Uri
        if (StringUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getAbsoluteImagePath((Activity) context, uri);
        }
        String ext = AdvancedFileUtils.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;

        // 照片命名
        String cropFileName = "virtual" + StringUtils.USER_ID
                + "_" + timeStamp + "." + ext;
        // copyProtraitName = cropFileName;

        // 裁剪頭像的絕對路徑
        // protraitPath = IMAGE_SAVE_PATH + cropFileName;

        File lImageSaveFile = new File(StringUtils.IMAGE_SAVE_PATH, cropFileName);
        cropUri = Uri.fromFile(lImageSaveFile);
        return cropUri;
    }

    /**
     * 拍照儲存的絕對路徑,當點選拍照的時候,不能存在系統預設的路徑,有可能無法訪問
     */
    public Uri getCameraTempFile() {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(StringUtils.IMAGE_SAVE_PATH);
            if (!savedir.exists()) {
                savedir.mkdir();
            }
        } else {
//            Toast.Long(mContext, R.string.text_save_photo_failed);
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA)
                .format(new Date());
        // 照片命名
        String cropFileName = "virtual" + StringUtils.USER_ID
                + "_" + timeStamp + ".jpg";

        // 裁剪頭像的絕對路徑
        File lImageSaveFile = new File(StringUtils.IMAGE_SAVE_PATH, cropFileName);
        Uri tempUri = Uri.fromFile(lImageSaveFile);
        return tempUri;
    }


    /**
     * 裁剪圖片
     * 儲存原圖和剪裁圖
     *
     * @param uri         絕對路徑
     * @param requestCode 請求碼
     * @param context     上下文
     */
    private Intent mIntent;

    public void doCropImage(Uri uri, Context context, int requestCode) {
        try {
            mIntent = new Intent("com.android.camera.action.CROP");
//            mIntent.setDataAndType(uri, "image/*");
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                String url = ImageUtils.getPath(context, uri);
                mIntent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
            } else {
                mIntent.setDataAndType(uri, "image/*");
            }
            mIntent.putExtra("crop", "true");
            mIntent.putExtra("scale", true);// 去黑邊
            mIntent.putExtra("scaleUpIfNeeded", true);// 去黑邊
            mIntent.putExtra("aspectX", 1);   // 設定裁剪的寬、高比例為9:9
            mIntent.putExtra("aspectY", 1);
            mIntent.putExtra("outputX", 300); // outputX,outputY是裁剪的寬、高度
            mIntent.putExtra("outputY", 300);

            getUploadTempFile(context, uri);
            mIntent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri);
            mIntent.putExtra("return-data", false); //若為false則表示不返回資料
//            mIntent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
//            mIntent.putExtra("return-data", false);
            mIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            mIntent.putExtra("noFaceDetection", true); // 關閉人臉檢測
            ((Activity) context).startActivityForResult(mIntent, requestCode);
        } catch (Exception e) {
//            Toast.Short(context, "剪裁失敗");
        }
    }

    public Uri getRealPath(Context context){
        String lRealFilePath = getRealFilePath(context, cropUri);  //將URL轉成真實的路徑
        return cropUri;
    }

    public String getRealFilePathString(Context context){
        return  getRealFilePath(context, cropUri);  //將URL轉成真實的路徑
    }

}


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


}

6.StringUtils:字串處理工具
public class StringUtils {

    public static String IMAGE_SAVE_PATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/ZSSX1_picture";

    public static boolean isEmpty(String string){
        return TextUtils.isEmpty(string);
    }

}

最後我們需要一個主函式去實現:
case R.id.tv_action_one:
                        Log.d("photo","tv_action_one");
                        startSelectPhotos();
                        break;
                    case R.id.tv_action_two:
                        Log.d("photo","tv_action_two");
                        startActionCamera();
                        break;
    /**
     * 照片 請求碼
     */
    public final static int CAMERA = 100;
    public final static int PICTURE = 101;
    public final static int UPLOADPICTURE = 102;
    private PhotoOperation mPhotoOperation = new PhotoOperation();
    public Uri mCameraTempFileUri;

    /**
     * 從手機中選擇
     */
    private void startSelectPhotos() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//		開啟相簿(方式二)
//      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//		intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "選擇圖片"), PICTURE);
    }

    /**
     * 拍照
     */
    private void startActionCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        if (mCameraTempFileUri == null) {
        mCameraTempFileUri = mPhotoOperation.getCameraTempFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraTempFileUri);
        startActivityForResult(intent, CAMERA);
    }

    public static Uri imgUri = null;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case CAMERA:
                imgUri = mCameraTempFileUri;
                mPhotoOperation.doCropImage(imgUri, this, UPLOADPICTURE);
                break;
            case PICTURE:
                imgUri = data.getData();
                mPhotoOperation.doCropImage(imgUri, this, UPLOADPICTURE);
                break;
            case UPLOADPICTURE:
                Log.d("photo","更換頭像");
                Uri lUri = mPhotoOperation.getRealPath(this);
                Bitmap mBitmap = null;
                try {
                    Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(lUri));
                    mBitmap = Bitmap.createScaledBitmap(bmp, 100, 100, true);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
               mImageView.setImageBitmap(mBitmap);
                pictoBig = true;
                break;
            default:
                break;
        }
    }

最後看看效果: