cssimagegwtgwt-bootstrap

dynamic css background-image in gwt


I have a page with some offers and I want to display for each offer one photo as thumbnail. The thumbnail image has fixed width and height, so I need to resize and crop original image. I would like to use background-size: cover.

My problem is that I'm using GWT-Bootstrap and I need to have source of image dynamic. The example code:

<b:Thumbnail size="3">
    <b:Image ui:field="image" />
    <b:Paragraph ui:field="text" />
    <b:Button ui:field="button" />
</b:Thumbnail>

for each Offer do:

@UiField Image image;

private void renderOffer(final Offer offer) {
    String photo = offer.getPHOTO();
        image.setUrl("images?img=" + photo);
    }
            ...
}

Image is returned by servlet:

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String img = request.getParameter("img");
    ServletContext sc = getServletContext();

    String mimeType = sc.getMimeType(img);
    response.setContentType(mimeType);

    Properties parameters = ParametersLoader.getParameters();
    File file = new File(parameters.getProperty("imageUrlPath") + img);
    response.setContentLength((int)file.length());

    FileInputStream in = new FileInputStream(file);
    OutputStream out = response.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }
    in.close();
    out.close();
}

How to replace <b:Image ui:field="image" /> with div with css like:

.myDiv {
  background-image:  url(somehow received dynamic url?);
  background-size:   cover;  
  background-repeat: no-repeat;
}

Solution

  • You can use Label instead of Image:

    <b:Label ui:field="image" styleName="myDiv" />
    

    In your CSS:

    .myDiv {
      background-size:   cover;  
      background-repeat: no-repeat;
    }
    

    Then in your code:

    image.getElement().getStyle().setBackgroundImage("images?img=" + photo);