最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to save an image drawn on the canvas in Electron.js - Stack Overflow

programmeradmin0浏览0评论

my code to save image is:

var fs = require('fs');
const dialog = require('electron').remote.dialog;
var canvasBuffer = require('electron-canvas-to-buffer');

dialog.showSaveDialog({title:'Testing a save dialog',defaultPath:'image.jpg'},saveCallback);

function saveCallback(filePath) {
  // as a buffer
  var buffer = canvasBuffer(canvas, 'image/png')
  // write canvas to file
  fs.writeFile('image.png', buffer, function (err) {
    throw err
  })
}

I am not able to save the image drawn on the canvas

the error window shows

img.toPNG is not a function

error.

my code to save image is:

var fs = require('fs');
const dialog = require('electron').remote.dialog;
var canvasBuffer = require('electron-canvas-to-buffer');

dialog.showSaveDialog({title:'Testing a save dialog',defaultPath:'image.jpg'},saveCallback);

function saveCallback(filePath) {
  // as a buffer
  var buffer = canvasBuffer(canvas, 'image/png')
  // write canvas to file
  fs.writeFile('image.png', buffer, function (err) {
    throw err
  })
}

I am not able to save the image drawn on the canvas

the error window shows

img.toPNG is not a function

error.

Share Improve this question edited Oct 8, 2018 at 9:48 pergy 5,5311 gold badge24 silver badges39 bronze badges asked Oct 7, 2018 at 19:49 Affsan AbbrarAffsan Abbrar 1211 silver badge9 bronze badges 1
  • what is canvas which you feed to canvasBuffer (most probably that's the problematic data). Plz share a testable code. – pergy Commented Oct 8, 2018 at 9:49
Add a comment  | 

2 Answers 2

Reset to default 12

I assume that your canvas is correct and already drawn. So you don't need canvas-to-buffer. Try this approach. (I used jpg, but png works as well)

function saveCallback(filePath) {
    // Get the DataUrl from the Canvas
    const url = canvas.toDataURL('image/jpg', 0.8);

    // remove Base64 stuff from the Image
    const base64Data = url.replace(/^data:image\/png;base64,/, "");
    fs.writeFile(filePath, base64Data, 'base64', function (err) {
        console.log(err);
    });
}

Don't use toDataURL(). There is toBlob() which is designed for this purpose. Something like this (totally untested):

async function saveCallback(filePath) {
  const blob = await new Promise(
     (resolve) => canvas.toBlob(blob => resolve(blob), "image/jpg", 0.8)
  );
  const buffer = new Buffer(await blob.arrayBuffer());
  
  await new Promise(
      (resolve, reject) => fs.writeFile(
           filePath, 
           buffer, 
           "binary", 
           (err) => {
               if (err === null) {
                   resolve();
               } else {
                   reject(err);
               }
           }
       )
   );
}
发布评论

评论列表(0)

  1. 暂无评论