Setting dynamic image in CSS background-image

I’m trying define dynamically the image url in CSS background-image to one Element container like VerticalLayout, HorizontalLayout or Div.

I’m get the StreamResource like this:

StreamResource imageResource = new StreamResource("backgroud.jpg", 
        		() -> getClass().getResourceAsStream("/static/backgrounds/w_"+i+".jpg"));

i is a random integer 1 to 10 interval.

this.getStyle().set("background-image", "url('"+image.getSrc()+"')");

I get back the dynamic image address with one Image component and method getSrc() that return to me one dynamic address. But I can’t access or route Vaadin Application to this address.

Alternativatelly, I’m try access with File too:

File f = new File(getClass().getResource("/static/backgrounds/w_1.jpg").getPath());
this.getStyle().set("background-image", "url('"+f.toURI()+"')");

But I don’t have success in both codes. The CSS return the message that image can’t load.

Any suggestions on how to do it?

I resolved the question. I don’t know if this solution is the best and more elegant way for resolve the problem, but works for me.

Follow the code:

Image img = new Image(getBackgroundImage(), null);
		
this.getStyle().set("position", "relative");
this.getStyle().set("background-position", "center");
this.getStyle().set("background-size", "cover");
this.getStyle().set("background-repeat", "no-repeat");
this.getStyle().set("background-image", "url('"+img.getSrc()+"')");

// the two lines bellow are enought for solution
add(img);
img.setVisible(false);

In the first moment, I don’t add Image component into the VerticalLayout container, and obviosly because of this, the dynamic image are not acessible in application. When I add Image component, this image need be not visible img.setVisible(false);, for obviously reasons.