通过Glide将图像从图库加载到ImageView中

问题描述 投票:-1回答:1

我的目的是用户从他们的图库中选择一个图像。我想使用Glide库将此图像加载到ImageView中。它似乎无法处理传递给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);
        }

    }
}

我在Glide控制台中收到以下错误:

I/Glide: Root cause (1 of 2)
java.io.FileNotFoundException: /document/image:2442 (No such file or directory)
android imageview uri android-glide
1个回答
0
投票

因为返回的uri是以/ document / image形式:1234,Glide无法正确识别路径,需要将其转换为绝对路径。你可以试试这个!

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());
}
© www.soinside.com 2019 - 2024. All rights reserved.