简体   繁体   English

从图库中选取图像并设置为imageview

[英]Picking image from gallery and set to imageview

I'm trying to pick image from gallery and set it to imageview. 我正在尝试从图库中选择图像并将其设置为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();
    }

}

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. 我正在使用三星S4,而Android版本是5.0.1。 I think, problem is about cursor, but can't fix it. 我认为,问题是关于光标,但无法修复它。 Please help me. 请帮我。

Here is code I have used for Picking Gallery Image then display it to ImageView . 这是我用于Picking Gallery Image的代码,然后将其显示给ImageView You can use according to your need. 您可以根据自己的需要使用。

Here is method for opening Gallery Intent. 这是打开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);
}

then your onActivityResult() method should be like this. 那么你的onActivityResult()方法应该是这样的。 in this method mContext refers Context of Activity . 在此方法中, mContext引用Activity Context。 if Activity name is MainActivity then you can use MainActivity.this 如果Activity名称是MainActivity那么您可以使用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);
           }      
      } 
}

Here is GetFilePathFromDevice class used in onActivityResult() method to get file path of selected image from Gallery. 这是在onActivityResult()方法中使用的GetFilePathFromDevice类,用于从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());
    }
}

I hope it helps you. 我希望它对你有所帮助。

Try this 尝试这个

private static int RESULT_LOAD_IMAGE = 1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM