我想要做toDataUrl()
的畫布,它給出了base64
的數據。我想將它作爲png
存儲。我可以從base64中獲取轉換後的二進制數據,但我無法使用NodeJs服務將其寫入文件。如何使用node.js將二進制數據寫入文件?
如果我直接寫入base64數據到文件,所有的數據都可以寫入,但是不可能是png
吧?我想存儲要存儲的二進制數據。怎麼做?
代碼片段:
var strData = this.drawingCanvas.getContext().canvas.toDataURL();
var data = strData.replace(/^data:image\/\w+;base64,/, "");
var imgData = this.decode(data); // decode(data) is DEFINED BELOW
this.call({filePath:'<path>/image.png', data: imgData},
{method:"writeFile"});`
`utf8decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
},`
`_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/=",
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = this.utf8decode(output);
return output;
},`
/**************************************************
wRITEfILEaaSSISTANT.JS
***************************************************/
var WriteFileAssistant = function(){};
WriteFileAssistant.prototype.run = function(future, subscription) {
var fs = IMPORTS.require('fs');
var filePath = this.controller.args.filePath;
var f = subscription.get();
f.result = {reply: data};
var fd = fs.openSync('<path>/image.png', 'a+');
//var data = fs.writeSync(fd, g, null, encoding='utf8');
//this.controller.args.data - Image data (binary)
var buff = new Buffer(this.controller.args.data, 'binary');
//tried also with 'base64'
fs.write(fd, buff, 0, buff.length, 0, function(err,written){
});
var f = subscription.get();
f.result = {reply: data};
你可以發表一些你迄今爲止的保存代碼,所以我們有一些工作? – loganfsmyth
謝謝你,我已經發布了上面的代碼。 – Kantesh
你發佈的內容是可讀的,但請查看代碼格式標準。你應該用4個空格縮進所有東西,而不是用''標記來包裝它們。 – loganfsmyth