0

我在咖啡脚本中有这段代码:

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 个字节写入磁盘并且它会破坏图像. 我一直在尝试将缓冲区编码设置为“二进制”和其他所有内容,但它仍然被写入两个字节 - 所以请告诉我使用节点将二进制数据写入磁盘的正确方法是什么。

4

1 回答 1

0

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
于 2013-04-08T22:45:41.957 回答