简体   繁体   English

从图库上传图像并在 AlertDialog 中显示

[英]Upload image from gallery and display in AlertDialog

I'm trying to display an image uploaded from the gallery in an AlertDialog but it's not working for me right now.我正在尝试在 AlertDialog 中显示从图库上传的图像,但它现在不适用于我。

My code:我的代码:

private void dispatchTakePictureIntent() {
        Intent imageGetter = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activityLauncher.launch(imageGetter);
    }

ActivityResultLauncher<Intent> activityLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> {
        Uri selectedImage = result.getData().getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};//Array size of 1, and we put in a string
        Cursor cursor = getContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String user_image_path = cursor.getString(columnIndex);
        myImageView = new ImageView(getContext());
        Picasso.get().load(user_image_path).fit().centerCrop().into(myImageView);
        AlertDialog.Builder builder =
                new AlertDialog.Builder(getContext()).
                        setMessage("Message above the image").
                        setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).
                        setView(myImageView);
        builder.create().show();
        cursor.close();
    });

The gallery opens up and I can choose a picture but after I choose a picture it goes back and a blank dialog with no image (the message is there) shows up.画廊打开,我可以选择一张图片,但在我选择一张图片后,它会返回并出现一个没有图像的空白对话框(消息在那里)。

I tried adding "file:/// " to the Picasso but that doesn't work.我尝试将“file:///”添加到毕加索,但这不起作用。

Thanks.谢谢。

Why not use the Uri directly to display the picture?为什么不直接使用Uri来显示图片呢? Just like:就像:

Uri selectedImage = result.getData().getData();
Picasso.get().load(selectedImage).fit().centerCrop().into(myImageView);

At the same time, it is worth noting that同时,值得注意的是

resolver.query()解析器.query()

is a I/O operation.是一个 I/O 操作。 It is not recommended to operate directly on the main thread不建议直接在主线程上操作

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

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