Converting byte array to image component

Hi,

I retrieve an image into a byte array in my application and want to display it in my UI. How do I do it?

Please help !!

Thank You
Dhaval Maheshwari.

Hi,
For displaying (and creating) images in Vaadin, check
ths chapter
out.

Sorry vaadin team, but I still don’t understand that chapter Johan Ånäs mention. I’ll like to share the other way I found resolving this and of course, asking someone to share step by step using Stream Resources. Thanks. Example encoding to Base64 the byte:

    Label image = new Label();
    image.setContentMode(ContentMode.HTML);
    image.setValue( // Java 8 Base64 encode
        "<div class=\"pleaseHelpWithStreamResources\">
            <img src=\"data:image/png;base64," +
            new String(Base64.getEncoder().encode(myByteArray)) +
            "\"/>
        </div>");
    image.setHeight(height);
    image.setWidth(width);
    layout.addComponent(image);

CSS styles:

.pleaseHelpWithStreamResources {
    height: 100%;
    width: 100%;
}
    
.pleaseHelpWithStreamResources img {
    height: 100%;
    width: 100%;
}

Sorry my English.

Your Label approach is probably ok. There is no single right way to do this. If you still want to use Image compinent you need to use ExternalResource for the Image, like

new ExternalResource("data:image/jpeg;base64,"+Base64.getEncoder().encode(myByteArray))+"\");

This new ExternalResource("data:image/jpeg;base64,"+Base64.getEncoder().encode(myByteArray))+"\"); seems wrong. The +"\" I can’t get to work. I don’t know if the intention was to add a \ at the end or a " at the end. Nor I understand why adding any of those.

That is true, in one of my addons I do it this way (using other Base64 encoder library though), the previous syntax is the Java 8 version, which has builtin Base64 support nowadays. The "" is just copy paste error, from code where I have complete html tag (putting image in Label).

htmlValue = “data:”+mimeType+“;base64,” + Base64.encodeBase64String(value);

https://github.com/vaadin/grid-renderers-collection-addon/blob/vaadin8/grid-renderers-collection-addon/src/main/java/org/vaadin/grid/cellrenderers/view/BlobImageRenderer.java