gpt4 book ai didi

javascript - 如何将 Canvas 数据保存到文件

转载 作者:IT老高 更新时间:2023-10-28 21:56:45 25 4
gpt4 key购买 nike

我正在使用 node.js 将 Canvas 保存到图像writeFile 中的 img 是通过在我的 Canvas 元素上使用 toDataURL 提取的。它不保存文件这是我的代码

var fs = IMPORTS.require('fs');
var path = IMPORTS.require('path');
path.exists('images/', function(exists){
if (exists) {

fs.writeFile('images/icon.png', img, function(err){
if (err)
callback({
error: false,
reply: err
});
console.log('Resized and saved in');
callback({
error: false,
reply: 'success.'
});
});
}
else {
callback({
error: true,
reply: 'File did not exist.'
});
}
});

最佳答案

这是一个文字示例,说明如何在 Nodejs 中将 Canvas 数据保存到文件中。变量 img 是由 canvas.toDataURL() 生成的字符串。我假设您已经知道如何将该字符串从浏览器发布到您的 Nodejs 服务器。

生成我使用的示例图像的 HTML 片段:

<canvas id="foo" width="20px" height="20px"></canvas>
<script>
var ctx = $('#foo')[0].getContext('2d');
for (var x = 0; x < 20; x += 10) {
for (var y = 0; y < 20; y += 10) {
if (x == y) { ctx.fillStyle = '#000000'; }
else { ctx.fillStyle = '#8888aa'; }
ctx.fillRect(x, y, 10, 10);
}
}
console.log($('#foo')[0].toDataURL());
</script>

Nodejs 片段解码 base64 数据并保存图像:

const fs = require("fs").promises;

(async () => {

// string generated by canvas.toDataURL()
const img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
+ "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
+ "3gAAAABJRU5ErkJggg==";

// strip off the data: url prefix to get just the base64-encoded bytes
const data = img.replace(/^data:image\/\w+;base64,/, "");

const buf = Buffer.from(data, "base64");
await fs.writeFile("image.png", buf);
})();

输出:

enter image description here

关于javascript - 如何将 Canvas 数据保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867534/

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