开发者

save html5 canvas element to file using webos

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 m开发者_JAVA百科y 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


data is a string which starts with data:image/png;base64, and the rest is the data in base64.

  1. Remove data:image/png;base64, from data
  2. Convert it from base64 to binary
  3. 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(...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜