GraphicImage is capable of presenting images that are created programmatically at runtime or images stored in a database.
<div class="card">
<h5>Static Image</h5>
<p:graphicImage name="images/nature/nature4.jpg" library="demo"/>
</div>
<div class="card">
<h5>StreamedContent</h5>
<p:graphicImage value="#{graphicImageView.image}"/>
</div>
<div class="card">
<h5>Rendered as DataURI / ViewScoped support</h5>
<p:graphicImage value="#{graphicImageView.imageAsByteArray}" stream="false"/>
</div>
<div class="card">
<h5>Optimized without buffering</h5>
<p:graphicImage value="#{graphicImageView.imageWithoutBuffering}"/>
</div>
<div class="card">
<h5>GraphicText</h5>
<p:graphicImage value="#{graphicImageView.graphicText}"/>
</div>
package org.primefaces.showcase.view.multimedia;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import javax.imageio.ImageIO;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Named;
@Named
@RequestScoped
public class GraphicImageView {
public StreamedContent getGraphicText() {
return DefaultStreamedContent.builder()
.contentType("image/png")
.stream(() -> {
try {
BufferedImage bufferedImg = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImg.createGraphics();
g2.drawString("This is a text", 0, 10);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
return new ByteArrayInputStream(os.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
return null;
}
})
.build();
}
/**
* Streamed: the image is loaded in a separate request (stream="true", the default).
*/
public StreamedContent getImage() {
return DefaultStreamedContent.builder()
.contentType("image/jpeg")
.stream(() -> readImage("nature5.jpg"))
.build();
}
/**
* Rendered as DataURI (stream="false"): the content type is determined from the bytes.
*/
public byte[] getImageAsByteArray() throws IOException {
try (InputStream is = readImage("nature6.jpg")) {
return is.readAllBytes();
}
}
/**
* Written directly to the response, without buffering it in memory first.
*/
public StreamedContent getImageWithoutBuffering() {
return DefaultStreamedContent.builder()
.contentType("image/jpeg")
.writer(os -> {
try (InputStream is = readImage("nature7.jpg")) {
is.transferTo(os);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.build();
}
private static InputStream readImage(String name) {
return FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/demo/images/nature/" + name);
}
}