gpt4 book ai didi

php - html5 Canvas toDataURL 返回空白图像

转载 作者:可可西里 更新时间:2023-10-31 22:47:35 28 4
gpt4 key购买 nike

从空白 Canvas 开始:

<canvas id='myCanvas' width='800' height='600'></canvas>

然后初始化 Canvas :

  function init_canvas(){
var canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
context.lineCap = 'round';
// fill it with white background
context.save();
context.fillStyle = '#fff';
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.restore();
return;
}

然后在 Canvas 上画一堆。

然后尝试在后端使用ajax和PHP将其保存到服务器。

在客户端:

var img = canvas.toDataURL('image/png');
// strip the leading garbage.
img.substr(img.indexOf(',')+1).toString();

将生成的字符串(即 base64 编码的 png)直接带到 PHP 和 base64_decode() 字符串...图像始终是正确的大小,但它上面没有任何绘图 - 只是一个透明图像。这似乎不是 PHP 中 base64_decode() 的问题,它似乎是安全问题或其他问题。它在 Firefox 4 和最新的 Chrome 中都失败了。

将生成的 png 图像转储到带有“image/png”标题的 firefox 会在错误控制台中产生:

Error: Image corrupt or truncated: http://somewhere.com/showimage.php
Source file: http://somewhere.com/showimage.php

但是...图像没有损坏或被 chop ,除非 toDataURL() 到处都坏了,因为 php 的东西只是 base64_decode() toDataURL() 的结果。

有什么想法吗?

谢谢!

最佳答案

你见过this comment吗?在 base64_decode?

的 PHP 文档中

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
$encodedData = str_replace(' ','+',$encodedData);
$decocedData = base64_decode($encodedData);
?>

关于php - html5 Canvas toDataURL 返回空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919181/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com