简体   繁体   English

通过 Glide 从 Gallery 加载图像到 ImageView

[英]Loading Image From Gallery Into ImageView via Glide

I have an intent where the user selects an image from their gallery.我有一个意图,让用户从他们的图库中选择一张图片。 I want to load this image into an ImageView using the Glide library.我想使用 Glide 库将此图像加载到 ImageView 中。 It seems like it can't handle the URI that is being passed into Glide它似乎无法处理传递给 Glide 的 URI

        addPhotos.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            ActivityCompat.requestPermissions(CreateEvacuationProcedureActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);

            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, OPEN_DOCUMENT_CODE);
        }
    });



    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
        if (data != null) {
            // this is the image selected by the user
            Uri imageUri = data.getData();
            System.out.println(new File(imageUri.getPath()));


            Glide.with(this)
                    .load(imageUri.getPath()) // Uri of the picture
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            System.out.println(e.toString());
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(imageOne);
        }

    }
}

I am getting the following error in the console from Glide:我在 Glide 的控制台中收到以下错误:

I/Glide: Root cause (1 of 2)
java.io.FileNotFoundException: /document/image:2442 (No such file or directory)

Because the uri that's returned is in the form /document/image:1234, Glide cannot correctly identify the path,need to convert it to an absolute path.因为返回的uri格式为/document/image:1234,Glide无法正确识别路径,需要转为绝对路径。 you can try this!你可以试试这个!

String documentId = DocumentsContract.getDocumentId(uri);
if(isDocument(uri)){
    String id = documentId.split(":")[1];
    String selection = MediaStore.Images.Media._ID + "=?";
    String[] selectionArgs = {id};
    filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
}

private boolean isDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

Here is what I have done in Kotlin这是我在科特林所做的

Code to select image:选择图像的代码:

val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, 9998)

Code to loadImage into ImageView using Glide.使用 Glide 将图像加载到 ImageView 的代码。

        val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)

        val cursor: Cursor? = context?.contentResolver?.query(
            backgroundUrl, filePathColumn, null, null, null
        )
        cursor?.moveToFirst()

        val columnIndex: Int? = cursor?.getColumnIndex(filePathColumn[0])
        val filePath: String? = columnIndex?.let { cursor?.getString(it) }
        if (cursor != null) {
            cursor.close()
        }


        context?.let {
            Glide.with(it)
                .load(File(filePath)).into(YOUR_IMAGE_VIEW_ID)
        }

Please also note that you will need to implement runtime permission (read/write external storage) for running your app on Android 6.0 Marshmallow (API 23) or later.另请注意,您需要实施运行时权限(读/写外部存储)才能在 Android 6.0 Marshmallow (API 23) 或更高版本上运行您的应用程序。

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

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