Load a PNG image file for display on a Vaadin Flow layout as a Image object

Viewed 3599

Vaadin Flow offers an Image class, representing an HTML img tag.

If I have a file named logo.png stored in the resources folder of my Vaadin 12 app, how do I load that file for display as an Image on a layout?

The example for Image in the Vaadin 8 Sampler shows code no longer relevant as I cannot find a ClassResource class in Flow.

2 Answers

You can put that logo under what your build tool/setup considers a root for web resources under the directory frontend/... and then reference that resource like so:

new Image("frontend/images/logo.png", "Acme Inc. Logo")

If your resource is not located inside the root for web resources, this doc page gives a hint on using a com.vaadin.flow.server.StreamResource to provide the data by an java.io.InputStream:

StreamResource res = new StreamResource("logo-image.png", () -> {
    // eg. load image data from classpath (src/main/resources/images/image.png)
    return MainView.class.getClassLoader().getResourceAsStream("images/image.png");
});
Image imageFromStream = new Image( res,"Alternativ text description for logo image");
add(imageFromStream);
Related