I have this code in 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()
I'm trying to make a ppm image class, and I have a problem with saving the image to disk. So I first create Uint8Clamped array to keep the pixels data, then wrap it with a Buffer to be able to write it to disk later. And I set all pixels to some value to have some initial color in a loop. And as long as the value is in range 0..127 everything is fine, every byte is written to file as one byte, but when the value is bigger then 127 - every byte is written as 2 bytes to disk and it breaks the image. I've been trying to set the buffer encoding to 'binary' and everything else but it still gets written as two bytes - so plz tell me what is the correct way to write binary data to disk using node.
fs.write expects its arguments to be a Buffer. You are also missing an argument. Really you should just use fs.writeFile for simplicity though.
// 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