最完整的获取android手机图片并显示到控件的解决方案

来源:互联网 发布:stc15单片机最小系统图 编辑:程序博客网 时间:2024/05/21 12:18

手机上的本地图片资源分为两种,一种是从本地相册获取,一种是从本地相机拍照获取。

1、获取图片很简单,调用系统提供的Intent对象,启动本地相册和照相机功能。

代码如下:

 //开始拍照    private void startCamera() {        try{            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);            if(intent.resolveActivity(getPackageManager()) != null){                imageUri = setFileURI();//给即将拍照获取的照片命名,并返回它的uri                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);                startActivityForResult(intent,CAMERA_REQUEST);            }        }catch (ActivityNotFoundException e){            e.printStackTrace();        }    }
//给图片统一定义一个存放位置    private Uri setFileURI(){        //创建照片的存储目录        PHOTO_DIR.mkdirs();        String fileName = getFileName();        //给照片命名        File file = new File(PHOTO_DIR,fileName);        return Uri.fromFile(file);    }
//用当前时间作为拍照得到的照片的名字    protected String getFileName(){        Date date = new Date(System.currentTimeMillis());        SimpleDateFormat sdf = new SimpleDateFormat("'img'_yyyy-MM-dd HH:mm:ss", Locale.CHINA);        return sdf.format(date)+".jpg";    }

 //从相册获取图片    private void getPhotoFromAlbum() {        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);        intent.setType("image/*");        startActivityForResult(intent,PHOTOALBUM_REQUEST);    }

2、获取图片的路径。

对于拍照获取的图片,我们前面已经把图片的uri放到imgeUri里了,直接取出即可使用。

对于从本地相册取回的图片,可以从OnActivityResult方法中的Intent data中取回图片Uri

imageUri = data.getData()。

下面就是获取图片的路径了。

int sdkVersion = Build.VERSION.SDK_INT;
if(sdkVersion >= 19){//android 5.0以上直接返回的是图片的路径   path = getPath_above19(this,imgUri);//或者直接使用path = imgUri.getPath();  }else{    path = getPath_below19(imgUri);  }
 /**     * API19以下获取图片路径的方法     * @param uri     */    private String getFilePath_below19(Uri uri) {        //这里开始的第二部分,获取图片的路径:低版本的是没问题的,但是sdk>19会获取不到        String[] proj = {MediaStore.Images.Media.DATA};        //好像是android多媒体数据库的封装接口,具体的看Android文档        Cursor cursor = getContentResolver().query(uri, proj, null, null, null);        //获得用户选择的图片的索引值        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);        System.out.println("***************" + column_index);        //将光标移至开头 ,这个很重要,不小心很容易引起越界        cursor.moveToFirst();        //最后根据索引值获取图片路径   结果类似:/mnt/sdcard/DCIM/Camera/IMG_20151124_013332.jpg        String path = cursor.getString(column_index);        System.out.println("path:" + path);        return path;    }
/**     * APIlevel 19以上才有     * 创建项目时,我们设置了最低版本API Level,比如我的是10,     * 因此,AS检查我调用的API后,发现版本号不能向低版本兼容,     * 比如我用的“DocumentsContract.isDocumentUri(context, uri)”是Level 19 以上才有的,     * 自然超过了10,所以提示错误。     * 添加    @TargetApi(Build.VERSION_CODES.KITKAT)即可。     *     * @param context     * @param uri     * @return     */    @TargetApi(Build.VERSION_CODES.KITKAT)    public  static String getPath_above19(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];                }                // TODO handle non-primary volumes            }            // 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;    }    /**     * @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());    }

3、处理图片。

从本地获取的图片大小往往不符合我们的要求,我们可以做一些压缩处理。

  /**     * 压缩图片大小     * @param path 图片的路径     * @return     */    private Bitmap decodeSampleBitmap(String path) {        //refundPhoto是将要呈现图片的ImageView控件        int targetW = refundPhoto.getWidth();        int targetH = refundPhoto.getHeight();        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeFile(path,options);        int photoW = options.outWidth;        int photoH = options.outHeight;        //获取图片的最大压缩比        int scaleFactor = Math.max(photoW/targetW,photoH/targetH);        options.inJustDecodeBounds = false;        options.inSampleSize = scaleFactor;        options.inPurgeable = true;        Bitmap bitmap = BitmapFactory.decodeFile(path,options);       return  bitmap;    }

4、图片显示到ImageView.

Bitmap bm = decodeSampleBitmap(path);                        refundPhoto.setImageBitmap(bm);


0 0
原创粉丝点击