如何将图像文件加载到 ImageView? [英] How to load Image file to ImageView?

查看:58
本文介绍了如何将图像文件加载到 ImageView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在从文件选择器中选择图像文件后立即显示该文件.文件选择器仅限于 .png 和 .jpg 文件,所选文件存储在 File 类型的变量中.为此,我设置了一个 ImageView,我希望用这个新文件设置图像,唯一的问题是它的类型是 File 而不是 Image.

I am attempting to display an image file as soon as it is selected from a file chooser. The file chooser is restricted to .png and .jpg files with the selected files being stored in a variable of type File. To do this I have set up an ImageView, and I wish to set the image with this new file only problem is it is of type File not Image.

如何实现?到目前为止的代码...

How can this be achieved? Code so far...

    public void fileSelection(){

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select Profile Picture");
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*jpg"));
        File selectedFile = fileChooser.showOpenDialog(null);
        File selectedFileInput = selectedFile;

        if(selectedFile != null) {
            selectedFileOutput.setText("File selected: " + selectedFile.getName());
            previewPicture.setImage();
        } else {
            selectedFileOutput.setText("Please select a profile picture...");
        }
    }

推荐答案

您可以使用

Image image = new Image(selectedFile.toURI().toString());

然后把它放在ImageView中:

previewPicture.setImage(image);

其他构造函数对加载图像所需的资源提供更多控制.如果您想强制图像为特定大小,您可以在加载时调整它的大小,如果用户选择大图像但您只想显示缩小版本,这将节省内存.此外,加载大图像可能需要一些时间,因此您不应在 UI 线程上加载它.获取 URL 字符串版本的 Image 构造函数可以选择在后台线程中自动加载图像.下面强制宽度和高度都不超过 240 像素(同时保持原始纵横比),并在后台加载图像(从而不阻塞 UI):

Other constructors offer more control over resources required for loading the image. If you want to force the image to be a certain size, you can resize it on loading, which will save memory if the user chooses a large image but you only want to display a scaled-down version. Additionally, loading a large image may take time, so you should not load it on the UI thread. The Image constructors taking string versions of URLs have options to automatically load the image in a background thread. The following forces the width and height to be both no more than 240 pixels (while maintaining the original aspect ratio), and loads the image in the background (thus not blocking the UI):

Image image = new Image(selectedFile.toURI().toString(),
    240, // requested width
    240, // requested height
    true, // preserve ratio
    true, // smooth rescaling
    true // load in background
);

请参阅文档,了解其他可用的构造函数.

See the documentation for other available constructors.

这篇关于如何将图像文件加载到 ImageView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆