图片选择(相册,相机),简单工具类

没做7.0的适配,其他我自己测试了没啥问题,能用就用吧, 然后权限相关的,我之前写过一篇文章,处理权限的工具类。
http://www.jianshu.com/p/affa6855ba71

用的话,这样用就行了

ImageSelectHelper mHelper = new ImageSelectHelper(this);
selectHelper.setOnHandleImageListener(new ImageSelectHelper.HandleImageListener(){

@Override
public void handleTakePhoto(File imageFile) {

}

@Override
public void handleSelectAlbum(File imageFile) {
                                      
}

@Override
public void onFailedMessage(String message) {
       
} 

mHelper.takePhoto();

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mHelper.handleOnActivityResult(requestCode, resultCode, data);
}
public class ImageSelectHelper {
    private static final int REQUEST_CAMERA = 0X100;
    private static final int REQUEST_ALBUM = 0X200;
    private OnHandleImageListener mListener;
    private String path;
    private Object object;

    public ImageSelectHelper(@NonNull Object object){
        this.object = object;
        checkCallingObjectSuitability(object);
    }

    public void setOnHandleImageListener(OnHandleImageListener listener){
        this.mListener = listener;
    }

    /**
     * 拍照
     */
    public void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //判断是否有activity处理
        Uri photoFile = null;
        try {
            photoFile = Uri.fromFile(createImageFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFile);
        }

        executeRequest(object, takePictureIntent, REQUEST_CAMERA);
    }

    /***
     * 相册选择图片
     */
    public void selectAlbum(){
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        executeRequest(object, intent, REQUEST_ALBUM);
    }

    /**
     * 兼容fragment
     * @param object
     * @param intent
     * @param requestCode
     */
    private void executeRequest(@NonNull Object object, @NonNull Intent intent, int requestCode) {
        if (object instanceof android.app.Activity) {
            ((Activity) object).startActivityForResult(intent, requestCode);
        } else if (object instanceof android.support.v4.app.Fragment) {
            ((android.support.v4.app.Fragment) object).startActivityForResult(intent, requestCode);
        } else if (object instanceof android.app.Fragment) {
            ((android.app.Fragment) object).startActivityForResult(intent, requestCode);
        }
    }

    private String executeGetRealPath(@NonNull Object object, Uri uri) {
        if (object instanceof android.app.Activity) {
            return getRealFilePath((Activity) object, uri);
        } else if (object instanceof android.support.v4.app.Fragment) {
            return getRealFilePath(((android.support.v4.app.Fragment) object).getActivity(), uri);
        } else if (object instanceof android.app.Fragment) {
           return getRealFilePath(((android.app.Fragment) object).getActivity(), uri);
        }
        return "";
    }

    private void checkCallingObjectSuitability(@Nullable Object object) {
        if (object == null) {
            throw new NullPointerException("Activity or Fragment should not be null");
        }

        boolean isActivity = object instanceof android.app.Activity;
        boolean isSupportFragment = object instanceof android.support.v4.app.Fragment;
        boolean isAppFragment = object instanceof android.app.Fragment;
        if (!(isSupportFragment || isActivity || isAppFragment)) {
            throw new IllegalArgumentException("Caller must be an Activity or a Fragment.");
        }
    }

    public void handleOnActivityResult(int requestCode, int resultCode, Intent data){

        if(requestCode == REQUEST_CAMERA || requestCode == REQUEST_ALBUM){
            if(resultCode == Activity.RESULT_OK){
                switch (requestCode){
                    case REQUEST_CAMERA:
                        handleTakePhoto();
                        break;
                    case REQUEST_ALBUM:
                        handleSelectAlbum(data);
                        break;
                }
            }else if(mListener != null){
                mListener.onActionCancel();
            }
        }
    }

    private void handleSelectAlbum(Intent data) {
        if(null == data){
            if(mListener != null){
                mListener.onFailedMessage("文件不存在!");
            }
            return;
        }
        String path = executeGetRealPath(object, data.getData());
        if(TextUtils.isEmpty(path)){
            if(mListener != null){
                mListener.onFailedMessage("文件不存在!");
            }
            return;
        }
        File imageFile = new File(path);
        if (imageFile.exists() && mListener != null) {
            mListener.handleSelectAlbum(imageFile);
        } else if(mListener != null){
            mListener.onFailedMessage("文件不存在!");
        }
    }

    private void handleTakePhoto() {
        File imageFile = new File(path);
        if (imageFile.exists() && mListener != null) {
            mListener.handleTakePhoto(imageFile);
        } else if(mListener != null){
            mListener.onFailedMessage("文件不存在!");
        }
    }
    /**
     * 设置图片路径,生成图片文件
     * @return
     * @throws IOException
     */
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + ".jpg";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            if (!storageDir.mkdir()) {
                throw new IOException();
            }
        }
        File file = new File(storageDir, imageFileName);
        path = file.getAbsolutePath();
        return file;
    }
    /**
     * 获取相册选图后返回路径
     * @param context
     * @param uri
     * @return
     */
    public static 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;
    }

    interface OnHandleImageListener{
        void handleTakePhoto(File imageFile);
        void handleSelectAlbum(File imageFile);
        void onFailedMessage(String message);
        void onActionCancel();
    }

    public static abstract class HandleImageListener implements OnHandleImageListener{
        public void handleTakePhoto(File imageFile){}
        public void handleSelectAlbum(File imageFile){}
        public void onFailedMessage(String message){}
        public void onActionCancel(){}
    }
}

你可能感兴趣的:(图片选择(相册,相机),简单工具类)