How to load picture graphicImage primefaces into different component

Asked

Viewed 1,030 times

3

My idea at first is this:

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

Obs : Remembering that are two forms o h:form id="form-Foto" where this mine p:dialog and one other h:form id="form-cadastro" where I want to upload my photo automatically without having to upload follow 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>

follows below my class

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 !!!");
    }

}

In case anyone has ever done something like this or can help me I am grateful.

1 answer

0

You will get a call from this image on your web page:

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

Along with your button where confirms the image cut 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 his 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");

}
  • thanks Paul I will test here thanks so much for the help.

  • it didn’t work out but the following error = Cannot find Component for Expression "form-cadastro:comfoto" referenced from "j_idt22:form-Photo:j_idt34".

  • ie it does not find the component since it is after the update.

  • Strange, take a look if the form id is like form-cadastro and graphicImage id is as comfoto even, because it is this reference that he makes iddoform:iddocomponente

  • this as posted in the above code h:form id="form-registration" and in h:panelGrid id="panelGrid-fields-form" Columns="2" cellpadding="5" and inside p:graphicImage id="comfoto" and outside h:form id="form-Photo" where my p:commandButton value="Crop" action="#{photoCamBean.Crop}" update="Cropped msgs"

  • I did it this way = p:commandButton value="Crop" action="#{photoCamBean.Crop}" update=":form-registration:panelGrid-fields-form:comfoto, Cropped, msgs" icon="fa fa-scissors" style="color:blue" and nothing wrong percisti.

  • good guys, I did it this way = '<p:commandButton value="Crop" action="#{photoCamBean.Crop}" update="Cropped, msgs, :tabs:form-cadastre:comfoto" icon="fa fa-scissors" style="color:blue" />' which stopped the error, however the component to be updated is '<p:graphicImage id="comfoto" rendered="#{not Empty photoCamBean.newImageName}" library="Photos" name="#{photoCamBean.newImageName}. png" cache="false"/>' is not updating if someone can help me.

  • 1

    solved was just create an id for my p:tabview id = "tabs" and then update="Cropped msgs tabs"

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.