问题
here img variable is extracted from using Open Source Png Generation code here ..
http://www.xarg.org/2010/03/generate-client-side-png-files-using-javascript/ that is an alternative to canvas.toDataURL(); webOS does not support toDataURL so i had to use this lib.
here i have used this library and manipulated on my canvas image data pixel array
EditorAssistant.prototype.getDataURL = function(width,height,data){
var p = new PNGlib(height, width, 256); // construcor takes height, weight and color-depth
var background = p.color(0, 0, 0, 0); // set the background transparent
for (var i = 0, n = data.length; i < n; i += 4) {
var x = i * 10;
var y = Math.sin(i) * Math.sin(i) * 50 + 50;
// use a color triad of Microsofts million dollar color
p.buffer[p.index(Math.floor(x), Math.floor(y))] = p.color(data[i], data[i+1], data[i+2]);
}
return 'data:image/png;base64,'+p.getBase64() ;
}
honestly speaking i am newbie to node.js. i am just having an hit and trial APProach... i want to save my manipulated canvas object to image directory in my application.. the path does exists here and this code does not generate any error .. rater it give me success on callback and also return number of bytes written but i cant find an image named icon.png in the images folder... imgdata generated above is passed to this code as data..
var fs = IMPORTS.require('fs');
var path = IMPORTS.require('path');
var buff = new Buffer(data,'binary').toString('base64');
path.exists('images/', function(exists ){
if (exists) {
fs.open('images/icon.png', 'w', 666, function( e, id ) {
fs.write( id, buff, null, 'binary', function(err,written){
if(err)
callback({
error: false,
reply: err
});
if(written){
callback({
error: false,
reply: buff.toString()
});
}
fs.close(id, function(){
callback({
error: false,
reply: 'closed'
});
});
});
});
}
else {
callback({
error: true,
reply: 'File did not exist.'
});
}
}
})
thanks in advance
回答1:
data
is a string which starts with data:image/png;base64,
and the rest is the data in base64.
- Remove
data:image/png;base64,
fromdata
- Convert it from base64 to binary
- Save that binary buffer to file
Code
var buff = new Buffer(data.substr('data:image/png;base64,'.length), 'base64');
...
fs.write(id, buff, 0, buff.length, 0, function(...
来源:https://stackoverflow.com/questions/5874521/save-html5-canvas-element-to-file-using-webos