简体   繁体   English

如何使用 JavaScript 和 PHP 将 canvas 图像保存到服务器?

[英]How to save canvas image to server with JavaScript and PHP?

I'm struggling with saving my canvas image to server using JavaScript and PHP.我正在努力使用 JavaScript 和 PHP 将我的 canvas 图像保存到服务器。 I've tried multiple examples for both JS and PHP and it always fails.我已经为 JS 和 PHP 尝试了多个示例,但它总是失败。 There's conflicting advice on how to send image data to PHP script (base64, blob, FormData) and I'm not sure how best to communicate back to JS.关于如何将图像数据发送到 PHP 脚本(base64、blob、FormData)存在相互矛盾的建议,我不确定如何最好地与 JS 进行通信。 Currently, zero bytes PNG files are being saved to server and I'm not sure why.目前,零字节 PNG 文件正在保存到服务器,我不知道为什么。 I'd like to save generated canvas as a PNG on server and execute a command in JS on success.我想将生成的 canvas 保存为服务器上的 PNG,并在成功时在 JS 中执行命令。 How best to approach it?如何最好地接近它?

JS: JS:

var off_canvas = document.createElement('canvas');
off_canvas.width = 1080;
off_canvas.height= 1080;
var ctx = off_canvas.getContext("2d");
var brick = new Image();
brick.src = '../img/brick-white.jpg'; 
brick.onload = function(){
    var pattern = ctx.createPattern(this, "repeat");
    ctx.fillStyle = pattern;
    ctx.fill();
};
var base64img = off_canvas.toDataURL("image/jpeg");

fetch("../php/save_image.php", {
    method: "POST",
    image: base64img
})  .then(response => response.text())
    .then(success => console.log(success)) //execute command
    .catch(error => console.log(error));

PHP: PHP:

<?php
    $img = $_POST['image'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    
    if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/img")) {
        mkdir($_SERVER['DOCUMENT_ROOT'] . "/img", 0777, true);
    }
    
    $file = $_SERVER['DOCUMENT_ROOT'] . "/img/".time().'.png';
    
    $success = file_put_contents($file, $data);
    print $success ? $file.' saved.' : 'Unable to save the file.';
?>

in your js page add console.log(base64img);在你的 js 页面中添加console.log(base64img);

in your browser console, copy object.在浏览器控制台中,复制 object。 i use firefox, if you use something else, then from there copy console message.我使用 firefox,如果您使用其他东西,然后从那里复制控制台消息。

the message will be data:image/jpeg;base64,/9j/4AAQSk..... .消息将是data:image/jpeg;base64,/9j/4AAQSk.....

in your php page;在您的 php 页面中;

$img = "data:image/jpeg;base64,/9j/4AAQSk.....";
echo "<img src='$data' />"; exit;

now you will know the image is coming or not.现在您将知道图像是否出现。

if image is not showing you are not implementing the fetch method correctly如果图像未显示您未正确实现fetch方法

if image is showing, see if you are able to create dir/file.如果显示图像,请查看您是否能够创建目录/文件。 that is, apache has permission to create dir/file.即 apache 具有创建目录/文件的权限。 if you are able如果你能

After some fiddling with multiple options on both JS and PHP, this is what finally worked:在对 JS 和 PHP 的多个选项进行了一些摆弄之后,这就是最终奏效的方法:

JS JS

var off_canvas = document.createElement('canvas');
off_canvas.width = 1080;
off_canvas.height = 1080;
var off_ctx = off_canvas.getContext("2d");

off_ctx.beginPath();
off_ctx.rect(20, 20, 150, 800);
off_ctx.fillStyle = "red";
off_ctx.fill();

var brick = new Image();
brick.src =  "img/brick-white.jpg";
brick.onload = function(){
    var pattern = off_ctx.createPattern(brick, "repeat");
    off_ctx.fillStyle = pattern;
    off_ctx.fillRect(500, 0, 1000, 1000);
    
    // needs delay to fully render to canvas
    var timer = window.setTimeout(save_canvas(off_canvas), 500);
};

function save_canvas(c) {
    var b64Image = c.toDataURL("image/png");
    
    fetch("../php/save_image_b64.php", {
        method: "POST",
        mode: "no-cors",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body: b64Image
    })  .then(response => response.text())
        .then(success => console.log(success))
        .catch(error => console.log(error));
}

PHP PHP

<?php
    $img = file_get_contents("php://input"); // $_POST didn't work
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    
    if (!file_exists($_SERVER['DOCUMENT_ROOT'] . "/img")) {
        mkdir($_SERVER['DOCUMENT_ROOT'] . "/img", 0777, true);
    }
    
    $file = $_SERVER['DOCUMENT_ROOT'] . "/img/".time().'.png';
    
    $success = file_put_contents($file, $data);
    print $success ? $file.' saved.' : 'Unable to save the file.';
?>

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

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