Cropping images with JSF

PrimeFaces provides an imageCropper component to cut a certain region of an image to create a new one. The cropped part is passed to the bound backing bean value as a CroppedImage object which belongs to PrimeFaces api.  A simple example would be;

<p:imageCropper value="#{cropperBean.croppedImage}" image="ui/barca/campnou.jpg" />

When the page is rendered, a mask is applied onto the page and it’ll look like;

ImageCropper is an input component so when the form is submitted, the cropped part is passed to the cropperBean’s croppedImage property. From there on it’s developer’s responsibility to what to do with the cropped image. Here’s is an example that saves the new image to a folder on the server.


import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.primefaces.optimus.config.Scope;
import org.primefaces.optimus.config.annotations.Controller;
import org.primefaces.ui.component.imagecropper.CroppedImage;

@Controller(name="cropperBean", scope=Scope.REQUEST)
public class ImageCropperBean {

    private CroppedImage croppedImage;

    public CroppedImage getCroppedImage() {
        return croppedImage;

    public void setCroppedImage(CroppedImage croppedImage) {
        this.croppedImage = croppedImage;

    public String crop() {
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        String newFileName = servletContext.getRealPath("") + File.separator + "ui" + File.separator + "barca" + File.separator+ "croppedImage.jpg";

        FileImageOutputStream imageOutput;
        try {
            imageOutput = new FileImageOutputStream(new File(newFileName));
            imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
        } catch (FileNotFoundException e) {
        } catch (IOException e) {

        return null;

See ImageCropper in action

PrimeFaces online demo contains two imagecropper examples, one with regular submit and one with ajax powered image cropping.

One Response to Cropping images with JSF

  1. James says:

    Great tip. I think this would do well on JavaLobby. If you’re interested in reposting there, please contact me on james at and we can organise it


%d bloggers like this: