sharp icon indicating copy to clipboard operation
sharp copied to clipboard

how to store 16 bits buffer to PNG file ?

Open liokaiser opened this issue 3 years ago • 4 comments

how to store 16 bits buffer to PNG file?

I am trying to store the 16 bit data of a video iframe in a PNG file. I did not find in the documentation how to save correctly in a 16bit grayscale file

I use this code:

fs.readFile(rep+'frame1250.dat', (err, buf) => {
    let input = Buffer.from(buf.buffer);
    sharp( input, {
        raw: {
            width: width,
            height:  height,
            depth: 'ushort'
            channels : 1
        }
    })
    .toFile(rep+'frame1250.png');
})

The result file is in 24 bits, 3 channels

liokaiser avatar May 07 '22 16:05 liokaiser

Hi, did you see toColourspace()? The example provided in the docs should do what you need.

https://sharp.pixelplumbing.com/api-colour#tocolourspace

lovell avatar May 07 '22 17:05 lovell

Thanks Lovell, for the output format, it's perfect, I hadn't seen .toColourspace('grey16'). However, it's with the input buffer that I'm having trouble. I have a feeling that it doesn't accept 16bit typed arrays. When I pass a Uint16Array as a parameter it does not consider 16-bit data. I have to reduce the pixels to 8 bits for it to produce a coherent image, but I lose resolution.

fs.readFile(fichierFrame, (err, buf) => {
    let input = new Uint16Array(buf.buffer), tab = [];

    for(let i=0; i<input.length; i++){  tab.push(input[i]>>8)  }
    
    var tab8 = new Uint8Array(tab)

    sharp( tab8, {
        raw: {
            width:  width,
            height: height,
            channels : 1
        }
    })
    .toColourspace('grey16')
    .toFile(rep+'myframe.png', (err, info) => {
        if(err) console.log(err) else console.log(info)
        });
})

liokaiser avatar May 09 '22 00:05 liokaiser

When I pass a Uint16Array as a parameter it does not consider 16-bit data.

Please can you provide a sample input image and the expected vs actual output.

lovell avatar May 09 '22 07:05 lovell

Were you able to make any progress with this? If you still require help, please provide the requested information.

lovell avatar Jul 27 '22 09:07 lovell

Closing due to inactivity but please feel free to reopen with more details if further help is required.

lovell avatar Aug 13 '22 23:08 lovell