user6534435
user6534435

Reputation:

Javafx image from download link

I am uploading images to my backend and producing download links I want to download the image and display it in javafx I found this solution:

    ImageView imageView = ImageViewBuilder.create()
            .image(new Image(imageSource))
            .build();

But I am using JavaFx 11 and it seems there is no such thing as ImageViewBuilder in my javafx scene imageView package? Any ideas or an alternative way to do it?

Upvotes: 0

Views: 1261

Answers (1)

Slaw
Slaw

Reputation: 46180

The builder classes were deprecated a while ago. For more information see JDK-8124188, JDK-8092861, and this mailing list. That said, the Image class can still load remote images but you should use the constructors instead of the builders.

From the documentation (emphasis mine):

The Image class represents graphical images and is used for loading images from a specified URL.

Supported image formats are:

  • BMP
  • GIF
  • JPEG
  • PNG

Images can be resized as they are loaded (for example to reduce the amount of memory consumed by the image). The application can specify the quality of filtering used when scaling, and whether or not to preserve the original image's aspect ratio.

All URLs supported by URL can be passed to the constructor. If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.

Use ImageView for displaying images loaded with this class. The same Image instance can be displayed by multiple ImageViews.

So you can use:

String remoteUrl = ...;
Image image = new Image(remoteUrl);
ImageView view = new ImageView(image);

// or...
ImageView view = new ImageView(remoteUrl);

The second option takes advantage of the ImageView(String) constructor. Note that it precludes you from loading the image in the background (without custom code), which the constructors of Image provide an option for. If you want to control your own InputStream you can do that as well using the appropriate constructor of Image; don't forget to close the InputStream in this case.

Upvotes: 1

Related Questions