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

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

问题描述

从文件选择器中选择图像文件后,我正尝试显示它.文件选择器仅限于.png和.jpg文件,所选文件存储在File类型的变量中.为此,我已经设置了一个ImageView,我希望使用这个新文件设置图像,唯一的问题是它的类型是File not 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...");
        }
    }

推荐答案

您可以简单地通过以下方式创建图像

You can simply create an image with

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天全站免登陆