ImageCropper is used to extract a certain part of an image to create a new image.
Documentation<h:form> <p:growl id="msgs" showDetail="true"/> <h:panelGrid columns="2"> <p:imageCropper value="#{cropperView.croppedImage}" image="/resources/demo/images/nature/nature6.jpg" initialCoords="225,75,300,125" minSize="100,100" maxSize="250,250"/> <h:panelGroup id="cropped"> <p:graphicImage rendered="#{not empty cropperView.newImageName}" name="demo/images/crop/#{cropperView.newImageName}.jpg" /> </h:panelGroup> </h:panelGrid> <p:commandButton value="Crop" action="#{cropperView.crop}" update="cropped msgs" icon="pi pi-clone"/> </h:form>
@Named @RequestScoped public class CropperView { private CroppedImage croppedImage; private String newImageName; public CroppedImage getCroppedImage() { return croppedImage; } public void setCroppedImage(CroppedImage croppedImage) { this.croppedImage = croppedImage; } public void crop() { if(croppedImage == null) { return; } setNewImageName(getRandomImageName()); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); String newFileName = externalContext.getRealPath("") + File.separator + "resources" + File.separator + "demo" + File.separator + "images" + File.separator + "crop" + File.separator + getNewImageName() + ".jpg"; FileImageOutputStream imageOutput; try { imageOutput = new FileImageOutputStream(new File(newFileName)); imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length); imageOutput.close(); } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Cropping failed.")); return; } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "Cropping finished.")); } private String getRandomImageName() { int i = (int) (Math.random() * 100000); return String.valueOf(i); } public String getNewImageName() { return newImageName; } public void setNewImageName(String newImageName) { this.newImageName = newImageName; } }