20
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js png画像をファイルに書き出す

Last updated at Posted at 2015-06-07

Canvasで作成したpng画像をファイル出力する際のメモ

#Canvasを画像化
toDataURLメソッドで

//canvasのidがmycanvasだとして(jquery)

var imgdata=$("#mycanvas").toDataURL

//ajaxで渡す
$.ajax({
    url:"saveimg",
    data:{img:imgdata,filename,:"hoge.png"}
}).then(function(res){
    console.log(res);
});

#ファイルに出力する

saveimg.js
var express = require('express');
var router = express.Router();
var fs = require("fs");

/* GET users listing. */
router.post('/', function(req, res, next) {
    var base64Data = req.body.img.replace(/^data:image\/png;base64,/, "");
    
  fs.writeFile(req.body.path,base64Data,'base64',function(err){
      console.log(err);
      res.send(req.body.path+"書き込み完了");
  })
});

module.exports = router;

#ポイント

###1.受け取った画像データのヘッダから上記文字列を削除する
var base64 = req.body.img.replace(/^data:image\/png;base64,/, "");

###2.書き込み時に'base64'オプションを指定する
fs.writeFile(req.body.filename,base64Data,'base64',function(err){

これを指定しないと、開けない画像ファイルになってしまいます。

以上。

20
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?