本文介绍了从图库中选取图片并设置为imageview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试从图库中选择图像并将其设置为imageview.

I'm trying to pick image from gallery and set it to imageview.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {

            Log.e("1","1");
            // Get the Image from data

            Uri selectedImage = data.getData();
            Log.e("2","2");

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Log.e("3","3");

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            Log.e("4","4");
            // Move to first row
            cursor.moveToFirst();
            Log.e("5", "5");

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            Log.e("6","6");
            imgDecodableString = cursor.getString(columnIndex);
            Log.e("7","7");
            cursor.close();
            ImageView imgView = (ImageView) findViewById(R.id.imgView);
            Log.e("8","8");
            // Set the Image in ImageView after decoding the String
            imgView.setImageBitmap(BitmapFactory
                    .decodeFile(imgDecodableString));

        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

在日志中,它仅显示第三条日志,而在其后,显示吐司.我正在使用Samsung S4,而android版本是5.0.1.我认为问题出在光标上,但无法解决.请帮助我.

In logs it shows only third log and after that shows toast which in catch. I'm using Samsung S4, and android version is 5.0.1.I think, problem is about cursor, but can't fix it. Please help me.

推荐答案

这是我用来拾取图库图像,然后将其显示为ImageView的代码.您可以根据需要使用.

Here is code I have used for Picking Gallery Image then display it to ImageView. You can use according to your need.

这是打开图库意图的方法.

Here is method for opening Gallery Intent.

private static final int GALLERY_PHOTO = 111;

private void pickGalleryImage() {
     Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
     intent.setType("image/*");
     startActivityForResult(chooserIntent, GALLERY_PHOTO);
}

然后您的onActivityResult()方法应该是这样的.在此方法中,mContext引用Activity的上下文.如果Activity名称为MainActivity,则可以使用MainActivity.this

then your onActivityResult() method should be like this. in this method mContext refers Context of Activity. if Activity name is MainActivity then you can use MainActivity.this

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == GALLERY_PHOTO && resultCode == Activity.RESULT_OK) {
          if (data.getData() != null) {
                String filePath = GetFilePathFromDevice.getPath(mContext, data.getData());
                Bitmap bm = BitmapFactory.decodeFile(filePath);
                imgView.setImageBitmap(bm);
           }
      }
}

这是onActivityResult()方法中使用的GetFilePathFromDevice类,用于从图库中获取所选图像的文件路径.

Here is GetFilePathFromDevice class used in onActivityResult() method to get file path of selected image from Gallery.

public final class GetFilePathFromDevice {

    /**
     * Get file path from URI
     *
     * @param context context of Activity
     * @param uri     uri of file
     * @return path of given URI
     */
    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;
    }

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

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

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

希望对您有帮助.

这篇关于从图库中选取图片并设置为imageview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 08:10