3

我已经使用 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>
4

1 回答 1

3

您可以通过隐藏的输入字段将 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));
    }
}
于 2012-07-13T00:38:31.917 回答