java – How to load graphicImage primefaces image into different component

Question:

My idea at first is as follows:

I have a component p:dialog header="Foto Funcionário" widgetVar="dlg" resizable="false" , where I capture my image and crop it, as soon as this image is cropped I would like it to be automatically loaded into the main form ie h:panelGrid id="panelGrid-campos-form" columns="2"cellpadding="5"

Note: Remembering that there are two form h:form id="form-Foto" where my p:dialog and another h:form id="form-cadastro" where I want to upload my photo automatically without having to upload it follows my code below.

** Form Code Below:**

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>

<ui:composition template="/template/layoutBase.xhtml">

    <ui:define name="content">

        <p:tabView style="width:600px;height:500px;margin:auto;">

            <p:tab title="Cadastro de Funcionário">

                <!-- ******** Começo Formulário Para Captura de Foto **********-->
                    <h:form id="form-Foto">
                        <p:dialog header="Foto Funcionário" widgetVar="dlg" resizable="false">
                          <p:growl id="msgs" showDetail="true" />
                            <h:panelGrid columns="5" cellpadding="1">
                              <!-- ******** Começo Captura Imagem **********-->
                                <p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photo" />
                                <p:outputPanel id="photo">
                                    <p:imageCropper value="#{photoCamBean.croppedImage}"  rendered="#{not empty photoCamBean.filename}" image="/resources/Fotos/#{photoCamBean.filename}.png" initialCoords="100,52,300,125" maxSize="116,140" minSize="116,140" />
                                </p:outputPanel>
                              <!-- ******** Final Captura Imagem **********-->

                              <!-- ******** Começo Recorta Imagem **********-->
                                <h:panelGroup id="cropped">
                                    <p:graphicImage rendered="#{not empty photoCamBean.newImageName}" name="Fotos/#{photoCamBean.newImageName}.png"/>
                                </h:panelGroup>
                              <!--******** Final Recorta Imagem **********-->
                            </h:panelGrid>
                             <p:commandButton type="button" value="Capture" onclick="PF('pc').capture()" icon="fa fa-camera" style="color:blue" />
                             <p:commandButton value="Crop" action="#{photoCamBean.crop}" update="cropped msgs" icon="fa fa-scissors" style="color:blue" />
                        </p:dialog> 
                    </h:form>
                <!-- ******** Final Formulário Para Captura de Foto **********-->

                <!-- ******** Começo Campos de Cadastramento **********-->
                <h:form id="form-cadastro">

                    <h:panelGrid id="panelGrid-campos-form" columns="2"
                        cellpadding="5">

                        <p:outputLabel value="Foto:"/>
                        <h:outputLink value="javascript:void(0)" onclick="PF('dlg').show();" title="Foto">
                            <p:graphicImage id="semfoto" rendered="#{empty photoCamBean.newImageName}" library="Fotos" name="Modelo.jpg" cache="false"/>
                            <p:graphicImage id="comfoto" rendered="#{not empty photoCamBean.newImageName}" library="Fotos" name="#{photoCamBean.newImageName}.png" cache="false"/>
                        </h:outputLink>

                        <p:outputLabel value="Nome:" for="inputText-nome" />
                            <p:inputText id="inputText-nome" style="width:300px"
                                value="#{cadastroFuncionarioBean.pessoaModel.nome}" />

                            <p:outputLabel value="Cargo:" for="inputText-cargo" />
                            <p:autoComplete id="inputText-cargo" style="width:300px"
                                value="#{cadastroFuncionarioBean.funcionarioModel.cargo}"
                                completeMethod="#{cadastroFuncionarioBean.pesquisarCargos}" />

                            <p:outputLabel value="Login:" for="inputText-login" />
                            <p:inputText id="inputText-login" style="width:300px"
                                value="#{cadastroFuncionarioBean.usuarioModel.usuario}" />

                            <p:outputLabel value="Senha:" for="inputText-senha" />
                            <p:inputText id="inputText-senha" style="width:300px"
                                value="#{cadastroFuncionarioBean.usuarioModel.senha}" />

                            <p:spacer />

                            <p:commandButton value="Salvar" id="commandButton-salvar" icon="fa fa-save" style="color:blue" actionListener="#{cadastroFuncionarioBean.salvar}" update="panelGrid-campos-form" />

                    </h:panelGrid>

                    <p:messages showDetail="true" autoUpdate="true" closable="true" severity="warn" />
                    <p:messages autoUpdate="true" closable="true" severity="error" />
                    <p:messages showDetail="true" autoUpdate="true" closable="true" severity="info" />
                </h:form>
                <!-- ******** Final Campos de Cadastramento **********-->

            </p:tab>

            <p:tab title="Upload Xml Funcionário">
                <h:form id="form-upload" enctype="multipart/form-data">
                    <h:panelGrid id="panelGrid-upload-xml" columns="2" cellpadding="10">
                        <p:fileUpload value="#{cadastroFuncionarioBean.file}"
                            mode="simple" skinSimple="true" label="Selecionar" />
                        <p:commandButton value="Importar..." icon="fa fa-upload" style="color:blue" ajax="false"
                            actionListener="#{cadastroFuncionarioBean.UploadRegistros}" />
                    </h:panelGrid>
                </h:form>
            </p:tab>

        </p:tabView>

    </ui:define>

</ui:composition>


</html>

follow my class below

package br.com.view;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;

import javax.faces.FacesException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import org.primefaces.event.CaptureEvent;
import org.primefaces.model.CroppedImage;

import br.com.amarildo.util.NegocioException;

@ManagedBean
@ViewScoped
public class PhotoCamBean implements Serializable {
    private static final long serialVersionUID = 1L;

    private CroppedImage croppedImage;

    private String filename;

    private String newImageName;

    public CroppedImage getCroppedImage() {
        return croppedImage;
    }

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

    public String getNewImageName() {
        return newImageName;
    }

    public void setNewImageName(String newImageName) {
        this.newImageName = newImageName;
    }

    private String getRandomImageName() {
        int i = (int) (Math.random() * 10000000);

        return String.valueOf(i);
    }

    public String getFilename() {
        return filename;
    }

    public void oncapture(CaptureEvent captureEvent) {
        filename = getRandomImageName();
        byte[] data = captureEvent.getData();

        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        String newFileName = externalContext.getRealPath("") + "resources" + File.separator + "Fotos" + File.separator + filename + ".png";

        System.out.println("oncapture = "+newFileName);

        FileImageOutputStream imageOutput;
        try {
            imageOutput = new FileImageOutputStream(new File(newFileName));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
        } catch (IOException e) {
            throw new FacesException("Erro ao Captuar Imagem !!!", e);
        }
    }

    public void crop() {
        if (croppedImage == null) {
            return;
        }

        System.out.println("crop = " + filename);

        setNewImageName(filename);
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        String newFileName = externalContext.getRealPath("") + "resources" + File.separator + "Fotos" + File.separator + filename + ".png";

        FileImageOutputStream imageOutput;
        try {
            imageOutput = new FileImageOutputStream(new File(newFileName));
            imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
            imageOutput.close();
        } catch (Exception e) {
            NegocioException.MensagemErro("Falha ao Recortar Imagem !!!");
            return;
        }
            NegocioException.MensagemInformacao("Imagem Recortada com sucesso !!!");
    }

}

If anyone has done something like this or can help me, I'm grateful.

Answer:

You will have a callout of this image on your webpage:

<p:graphicImage id="comfoto" value="#{PhotoCamBean.getImage()}" stream="false" />

Along with your button where you confirm the cut of the image you can add in the update to update the other form:

<p:commandButton value="Crop" action="#{photoCamBean.crop}" update="form-cadastro:comfoto" icon="fa fa-scissors" style="color:blue" />

And in your PhotoCamBean you will pass the image reference to the web page:

public StreamedContent getImage() {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        //imageOutput é sua váriavel após o cropped!!
        BufferedImage buffered = ImageIO.read(imageOutput);

        ImageIO.write(buffered, "png", os);
    } catch (IOException ex) {
        Logger.getLogger(ComandoPivoBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");

}
Scroll to Top