使用 Tauri 中的 fs 模块将画布数据保存为 png 或 jpg。

huangapple go评论197阅读模式
英文:

Save canvas data as png or jpg in Tauri using fs module

问题

我想使用Tauri fs模块将我的画布数据保存到文件中。

这是我的代码,但它没有工作。

  1. const { writeBinaryFile, BaseDirectory } = window.__TAURI__.fs;
  2. var canvas = document.getElementById("myCanvas");
  3. var ctx = canvas.getContext("2d");
  4. var grd = ctx.createLinearGradient(0, 0, 200, 0);
  5. grd.addColorStop(0, "red");
  6. grd.addColorStop(1, "white");
  7. ctx.fillStyle = grd;
  8. ctx.fillRect(10, 10, 150, 80);
  9. async function IMAGE() {
  10. await writeBinaryFile('avatar2.png', canvas.toDataURL(), { dir: BaseDirectory.Document });
  11. }
  12. IMAGE()

我已经尝试将DataUrl转换为其他格式,我不知道是否会有帮助。

英文:

I want to save my canvas data to file using the Tauri fs module.

This is my code, but it didn't work.

  1. const { writeBinaryFile, BaseDirectory } = window.__TAURI__.fs;
  2. var canvas = document.getElementById("myCanvas");
  3. var ctx = canvas.getContext("2d");
  4. var grd = ctx.createLinearGradient(0, 0, 200, 0);
  5. grd.addColorStop(0, "red");
  6. grd.addColorStop(1, "white");
  7. ctx.fillStyle = grd;
  8. ctx.fillRect(10, 10, 150, 80);
  9. async function IMAGE() {
  10. await writeBinaryFile('avatar2.png', canvas.toDataURL(), { dir: BaseDirectory.Document });
  11. }
  12. IMAGE()

I have tried to convert DataUrl to other formats, I don't know if it will help or not.

答案1

得分: 1

你可以使用这个函数。

  1. function canvasDataToBinary(canvasData) {
  2. // 移除数据URL前缀(例如,'data:image/png;base64,')
  3. const data = canvasData.replace(/^data:image\/\w+;base64,/, '');
  4. // 将base64数据解码为二进制格式
  5. const binaryString = atob(data);
  6. // 从二进制字符串创建Uint8Array
  7. const length = binaryString.length;
  8. const binaryArray = new Uint8Array(length);
  9. for (let i = 0; i < length; i++) {
  10. binaryArray[i] = binaryString.charCodeAt(i);
  11. }
  12. return binaryArray;
  13. }
英文:

You can use this function.

  1. function canvasDataToBinary(canvasData) {
  2. // Remove the data URL prefix (e.g., &#39;data:image/png;base64,&#39;)
  3. const data = canvasData.replace(/^data:image\/\w+;base64,/, &#39;&#39;);
  4. // Decode the base64 data into binary format
  5. const binaryString = atob(data);
  6. // Create a Uint8Array from the binary string
  7. const length = binaryString.length;
  8. const binaryArray = new Uint8Array(length);
  9. for (let i = 0; i &lt; length; i++) {
  10. binaryArray[i] = binaryString.charCodeAt(i);
  11. }
  12. return binaryArray;
  13. }

huangapple
  • 本文由 发表于 2023年7月13日 21:22:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定