编程语言
首页 > 编程语言> > javascript-如何将toDataURL方法返回的画布内容作为图像存储在JSF中的磁盘上

javascript-如何将toDataURL方法返回的画布内容作为图像存储在JSF中的磁盘上

作者:互联网

我已经使用svg和javascript创建了图像,我希望用户能够保存它.如何将其发送到bean并保存?

查看代码:

<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>

解决方法:

您可以通过隐藏的输入字段将dataURL发送到支持Bean,如下所示:

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

并从您的javascript中设置inputHidden值的值,如下所示:

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

更新:toDataURL方法返回一个字符串,您可以将其与字符串保存在后备bean中,该字符串是base64编码的,因此可以将其解码回图像并保存到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));
    }
}

标签:html5,jsf-2,javascript
来源: https://codeday.me/bug/20191201/2078066.html