java image to file,如何将文件转换为图像以便在Java中的ImageView中显示?

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

and then place it in the ImageView:

previewPicture.setImage(image);

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值