简体   繁体   English

使用 canvas.toDataURL() 解码和保存图像

[英]Decoding and saving an image using canvas.toDataURL()

I'm working on a project which involves a user dragging and dropping boxes onto a div to create a layout.我正在处理一个项目,该项目涉及用户将框拖放到 div 上以创建布局。 Once the user is done, there's a button to press which takes the div and creates a canvas element from it using html2canvas, then it opens up in a new window as an image.用户完成后,有一个按钮可以按下,该按钮获取 div 并使用 html2canvas 从中创建一个画布元素,然后它在新窗口中作为图像打开。 This is fine, but I need it to save somewhere so it can be attached to an email and sent.这很好,但我需要将它保存在某个地方,以便将其附加到电子邮件并发送。 So far, all I have is the base64 encoded string which I cannot really do anything with.到目前为止,我所拥有的只是 base64 编码的字符串,我无法对其进行任何操作。

On the js side, I have:在js方面,我有:

html2canvas($('#canvas')).then(function(canvas) {
    $('canvas').addClass('canvas-layout');
    var src = canvas.toDataURL();
    var output=src.replace(/^data:image\/(png|jpg);base64,/, "");
    $.post( 'result.php', { data: output })
        .done( function(response) {
            console.log(response);
        }
    );
    return false;
});

where #canvas is the ID of the div.其中#canvas 是 div 的 ID。 In the result.php file, I have:在 result.php 文件中,我有:

$decodedData = base64_decode($_POST['data']);

$img = $decodedData;

$image = fopen($img, 'r');
file_put_contents("images/layout.png", $image);
fclose($image);

But I get a warning saying that I'm passing a string to fopen() - though this solution was given in another stackoverflow post and people seemed to get this working.但是我收到一条警告,说我正在将一个字符串传递给 fopen() - 尽管这个解决方案是在另一个 stackoverflow 帖子中给出的,人们似乎可以做到这一点。 Originally, the js just opened the image in a new window like so:最初,js 只是在新窗口中打开图像,如下所示:

window.open(src,'Image','width=1440,height=650,resizable=1');

But the URL in the browser window is the base64 encoded string which I can't do anything with.但是浏览器窗口中的 URL 是 base64 编码的字符串,我无能为力。

Is there a way of doing what I want to achieve?有没有办法做我想要实现的目标?

Thanks谢谢

OK - I've got it sorted.好的 - 我已经整理好了。 Basically, I needed to trim some other data off the string before being able to write it.基本上,我需要在能够写入之前从字符串中修剪一些其他数据。

So, I added this code before file_put_contents :所以,我在file_put_contents之前添加了这段代码:

$img = $_POST['data']; // Using the raw encoded string
$img = str_replace('data:image/png;base64,', '', $img); // removed unnecessary string
$img = str_replace(' ', '+', $img);
$data = base64_decode($img); // then decoded it
$file = "images/layout-file_". uniqid().".png"; // define new image name
$success = file_put_contents($file, $data); // finally write to server

This way it generates a uniquely named file and does not corrupt.这样它会生成一个唯一命名的文件并且不会损坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM