ImageCropper is used to extract a certain part of an image to create a new image.
<div class="card">
<h:form>
<p:growl id="msgs" showDetail="true"/>
<h:panelGrid columns="2" cellpadding="7">
<p:imageCropper value="#{cropperView.croppedImage}"
image="/resources/demo/images/nature/nature6.jpg"
initialCoords="225,75,300,125"
minSize="100,100"
maxSize="250,250"
zoomOnWheel="false"/>
<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" styleClass="mt-3" />
</h:form>
</div>
package org.primefaces.showcase.view.multimedia;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Named;
import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import io.quarkus.runtime.annotations.RegisterForReflection;
import org.primefaces.model.CroppedImage;
@Named
@RequestScoped
@RegisterForReflection(serialization = true)
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;
}
}