如何将文件转换为图像以便在Java中的ImageView中显示? [英] How to convert a File to Image for display in ImageView in java?

查看:486
本文介绍了如何将文件转换为图像以便在Java中的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...");
        }
    }


推荐答案

你只需创建一个图像

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
);

参见文档

这篇关于如何将文件转换为图像以便在Java中的ImageView中显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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