2013-04-07 56 views
0

我有這樣的代碼在coffescript:將緩衝區寫入文件 - 如何保存二進制格式?

fs = require 'fs' 

class PpmCanvas 


    constructor: (@width, @height, @fileName) -> 
     size = @width * @height * 3 

     array = new Uint8ClampedArray size 
     @buffer = new Buffer array 

     for element, index in @buffer 
      @buffer.writeUInt8 128, index 


    plot: (x, y, r, g, b) -> 
     true 

    save:() -> 
     header = new Buffer "P6 #{@width} #{@height} 255\n" 

     together = Buffer.concat([header, @buffer]) 

     fs.open @fileName, 'w', (err, fd) => 
      if err 
       throw err 

      fs.write fd, together.toString(), undefined, undefined, (err, written, buffer) => 
       fs.close fd 
canvas = new PpmCanvas 200, 200, 'image.ppm' 
canvas.save() 

我試圖做一個PPM圖像類,和我有圖像保存到磁盤的一個問題。因此,我首先創建Uint8Clamped數組來保留像素數據,然後用Buffer包裝它,以便稍後將其寫入磁盤。我將所有像素設置爲某個值以在循環中具有一些初始顏色。只要值在0..127的範圍內,一切都很好,每個字節都被寫入文件中作爲一個字節,但是當該值大於127時 - 每個字節都寫入2個字節到磁盤,並且它打破了映像。我一直試圖設置緩衝區編碼爲'二進制'和其他所有東西,但它仍然被寫爲兩個字節 - 所以PLZ告訴我什麼是使用節點將二進制數據寫入磁盤的正確方法。

+0

如果只是在沒有'.toString()'部分的情況下一起寫'會發生什麼? – loganfsmyth 2013-04-08 02:17:13

+0

@loganfsmyth:文件長度爲0 – agend 2013-04-08 11:41:48

+0

看起來你缺少'fs.write'的參數,我不確定它如何對'undefined'做出反應。也許試試'fs.write fd,在一起,0,together.length,0,(err,written,buffer) - >'。任何你不只是使用'writeFile'的理由? 'fs.writeFile @fileName,together' – loganfsmyth 2013-04-08 16:04:49

回答

0

fs.write預計它的參數是一個緩衝區。你也錯過了一個論點。不過,爲了簡單起見,你應該只使用fs.writeFile

// Add the missing 3rd arg and don't use 'undefined'. 
fs.write fd, together, 0, together.length, 0, (err, written, buffer) -> 

// Or just use this and drop the 'fs.open' call. 
fs.writeFile @fileName, together 
+0

再次感謝:) – agend 2013-04-08 22:56:57

相關問題