Cropping images with PrimeFaces

In this recipe, you will see how easy is to crop an image using PrimeFaces framework.

Getting ready

See the recipe Dynamic images with PrimeFaces.

How to do it...

PrimeFaces provides a component, named imageCropper, which crops a region of an image to create a new one. This component is used as shown next:

<p:imageCropper value="#{cropBean.cropImage}"
image="images/2009/rafael_nadal1.PNG" />

And the CropBean looks like the following:

package beans;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.CroppedImage;
@ManagedBean(name="cropBean")
@SessionScoped
public class CropBean {
private CroppedImage cropImage;
public CroppedImage getCropImage() {
return cropImage;
}
public void setCropImage(CroppedImage cropImage) {
this.cropImage = cropImage;
}
public String crop() {
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String fileName = servletContext.getRealPath("") + File.separator + "images" + File.separator + "2009" + File.separator+ "rafael_nadal1.PNG";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(fileName));
imageOutput.write(cropImage.getBytes(), 0,
cropImage.getBytes().length);
imageOutput.close();
} catch (FileNotFoundException e) {
//log error
} catch (IOException e) {
//log error
}
return null;
}
}

In the following picture, you can see what this PrimeFaces component looks like:

How to do it...

How it works...

As you can see the hard work is accomplished by the CropBean bean. Here the cropped image is obtained using a FileImageOutputStream object.

There's more...

The last two recipes present you some great facilities of the PrimeFaces framework. Don't forget that PrimeFaces comes with over 70 other amazing components and all of them are easy to use and understand.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Cropping_images_with_PrimeFaces.

You also may want to check:

PrimeFaces tag documentation: http://primefaces.prime.com.tr/docs/tag/

PrimeFaces home page: http://www.primefaces.org/

PrimeFaces ShowCase: http://www.primefaces.org:8080/prime-showcase/ui/imageCropperExternal.jsf

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

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