2016-02-18 89 views
0

我有一个带有许多指向外部图像源的图像标记的SVG(来自亚马逊s3存储桶)。我试图把它转换成PNG这样将svg保存为png,其中svg包含带有外部参考的图像

canvg(document.getElementById('myCanvas'), svg); 
var imgData = document.getElementById('myCanvas').toDataURL("image/png"); 

我收到此错误未捕获的SecurityError:无法执行对“HTMLCanvasElement” toDataURL“:被污染的画布不得出口。

我改变了我的s3存储桶设置(As mentioned here)。 添加这段代码canvg功能后

var img = new Image(); 
    img.setAttribute('crossOrigin', 'anonymous'); 
    img.src = document.getElementById('myCanvas').value; 

偶试过遍历所有的图像标签,并设置crossOrigin属性

我仍得到相同的错误。

+0

可能的重复http://stackoverflow.com/questions/29975138/how-can-i-get-pngbase64-with-images-inside-of-svg-in-google-charts – guest271314

+0

最后我得到了一个解决方案。我现在在服务器端进行转换(使用apache batik转码器库)没有更多的安全错误;) – Jerry

回答

2

我发现最好在服务器端进行转换,因为允许在亚马逊s3中交叉起源是一种安全威胁,即使给出了跨域权限,许多浏览器也不会支持.toDataUrl。

这就是我正在做的转换

在客户端

var s = new XMLSerializer().serializeToString(document.getElementById("svg")) 
var encodedData = window.btoa(s); 

而这个编码数据被传递到服务器端,我用蜡染库

做的实际转换SVG至PNG
BASE64Decoder decoder = new BASE64Decoder(); 
    byte[] image = decoder.decodeBuffer(encodedData); 
    String fileLocation = "C:\temp"; 
    String fileName = "New-" + System.currentTimeMillis(); 
    File file = new File(fileLocation +File.separator+ fileName + ".svg"); 
    FileOutputStream fop = new FileOutputStream(file); 
    if (!file.exists()) { 
     file.createNewFile(); 
    } 
    fop.write(image); 
    fop.flush(); 
    fop.close(); 
    PNGTranscoder transcoder = new PNGTranscoder(); 
    TranscoderInput tinput = new TranscoderInput(new FileInputStream(fileLocation + File.separator + fileName +".svg")); 
    OutputStream ostream = new FileOutputStream(fileLocation + File.separator + fileName +".png"); 
    TranscoderOutput toutput = new TranscoderOutput(ostream); 
    try { 
      transcoder.transcode(tinput, toutput); 
    } catch (TranscoderException e) { 
      System.out.println("error*"); 
      e.printStackTrace(); 
    } 
    ostream.close();