Cropping images

The imageCropper component provides image-cropping functionality by allowing us to crop a certain region of an image, which could either be a local image or an external image. After cropping, a new image is created. It contains the cropped region and it is assigned to a CroppedImage instance.

How to do it...

The org.primefaces.model.CroppedImage class belongs to the PrimeFaces API, and the structure of the class is as follows:

public class CroppedImage {
  String originalFilename;
  byte[] bytes;
  int left;
  int top;
  int width;
  int height;
}

A simple definition of the image cropper for cropping a local image would be as shown in the following code line. The value of the component is bound with an instance of CroppedImage.

<p:imageCropper value="#{imageCropBean.croppedImageSimple}"
  image="/resources/images/crop/primefaces.jpg" />

When hovered over the image, the cursor of the mouse will change to crosshairs for making the crop region selection. When the region is selected, it will be highlighted with a dashed canvas and the section left outside the region will be grayed out.

How to do it...

Note

Currently, image cropping is supported on an image provided with a relative path. Cropping cannot be applied on an image presented by a graphicImage component.

How it works…

The action method for the actual crop is defined in the following code snippet. This method retrieves the cropped image and converts it to an instance of the org.primefaces.model.StreamedContent class to display the image with the p:graphicImage component.

StreamedContent graphicText;

public String cropSimple() throws IOException {
  graphicText = new DefaultStreamedContent(new
    ByteArrayInputStream(croppedImage.getBytes()));
  return null;
}

Then the cropped image could be easily displayed by using the following code snippet:

<p:commandButton value="Crop" action="#{imageCropBean.cropSimple}"
  update="localCroppedImage"/>

The graphicText property created within the cropSimple method is an instance of StreamedContent, and it will be visualized with the <p:graphicImage> component.

Tip

The backing bean containing the graphicText property should be defined in the session scope. The reason behind it is that the image will be fetched in a separate request from the rest of the page content and in order to retrieve the cropped image, the content should be stored in the session context.

When the graphicImage component is fed with an image created dynamically, as it is done in the cropping examples, its cache attribute should be set to false in order to tell the regarding browser to disable caching on the resource.

The image that will be cropped should be shown in full size in order to be processed, so there is no way to limit the size of the image with a given width/height.

One other possible implementation for cropping the image could be for saving the image to the disk and showing the saved image via a media display component, such as graphicImage.

public String cropWithSave() {
  ServletContext servletContext = (ServletContext) 
    FacesContext.getCurrentInstance().getExternalContext().
    getContext();
  String newFileName = servletContext.getRealPath("") +
    File.separator + "resources" + File.separator + "images" +
    File.separator + "cropped.jpg";

  FileImageOutputStream imageOutput;
  try {
    imageOutput = new FileImageOutputStream(
      new File(newFileName));
    imageOutput.write(croppedImageSimple.getBytes(), 0,
      croppedImageSimple.getBytes().length);
    imageOutput.close();
  }
  catch (Exception e) {
    throw new FacesException(
      "Error in writing cropped image.", e);
  }
  return null;
}

There's more…

The initial coordinates of the cropped region drawn on the canvas of the image can be defined with the initialCoords attribute. The notation of the attribute should follow the x, y, w, h format, where x and y stand for the x and y coordinate values, and w and h stand for width and height.

The backgroundColor attribute defines the color of the background container with the default value as black. The backgroundOpacity attribute defines the opacity of the outer image while cropping. Its default value is 0.6, and the value should be between 0 and 1.

The minSize and maxSize attributes define the minimum width and height for the cropped region in pixels with the notation [width, height].

The aspectRatio attribute defines the ratio of the cropped region as width to height. To make it a square, the value should be set to 1.

The imageCropper component provides the ability to crop external images as well. By providing the absolute URL to the image with the image attribute, it is possible to crop the image.

PrimeFaces Cookbook Showcase application

This recipe is available in the demo web application on GitHub (https://github.com/ova2/primefaces-cookbook/tree/second-edition). Clone the project if you have not done it yet, explore the project structure, and build and deploy the WAR file on every Servlet 3.x compatible application server, such as JBoss WildFly or Apache TomEE.

The showcase for the recipe is available under http://localhost:8080/pf-cookbook/views/chapter7/cropImage.jsf.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.164.75