kinkajou
kinkajou

Reputation: 3728

How to store canvas content returned by toDataURL method as an image on disk in JSF

I have created image using svg and javascript I want user to be able to save it. How do I send this to bean and save it?

view code:

<script>
        var svg = $('#map').html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
            // strips off all spaces between tags

            canvg('cvs', svg, {        
                ignoreMouse: true, 
                ignoreAnimation: true
            });  
         var canvas  = document.getElementById('cvs');
         var img = canvas.toDataURL("image/png"); 
   </script>

<h:body>
        <center><div id="map"></div></center>
        <a href="#" id="saveBtn">SAVE</a>
        <canvas id="cvs" width="0" height="0" ></canvas>​  
        <h:form id="formId">
            <h:inputText id="inputId" value="#{bean.property}" />
            <h:commandButton id="buttonId" value="Button" action="#{bean.action}" />
        </h:form>
    </h:body>

Upvotes: 3

Views: 2752

Answers (1)

Ravi Kadaboina
Ravi Kadaboina

Reputation: 8574

You can send the dataURL to the backing bean via an hidden input field like this:

 <h:form>
    <h:inputHidden id="dataURL" value="#{userBean.dataURL}" />
    <h:commandButton value="Submit" action="#{userBean.submit}"/>
 </h:form>

and set the value of the inputHidden value from your javascript like this:

var dataURL = canvas.toDataURL("image/png");
var hidden = document.getElementById("dataURL");
hidden.value = dataURL;

UPDATE: The toDataURL method returns a string and you can save the same as string in the backing bean, the string is base64 encoded so it can be decoded back into an image and saved to disk at the root of the webapp:

public class UserBean implements Serializable {
    private String dataURL;
    public String getDataURL() {
    return dataURL;
}
public void setDataURL(String dataURL) {
    this.dataURL = dataURL;
}
    public void submit(){
      ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
      ServletContext servletContext = (ServletContext) external.getContext();
      String filename = servletContext.getRealPath("cloud.png");
      BASE64Decoder decoder = new BASE64Decoder();
      byte[] decodedBytes = decoder.decodeBuffer(dataURL.split("^data:image/(png|jpg);base64,")[1]);
      BufferedImage imag=ImageIO.read(new ByteArrayInputStream(decodedBytes));
      ImageIO.write(imag, "png", new File(filename));
    }
}

Upvotes: 3

Related Questions