1

In a Nodejs project, I am using PSD.js to generate a png from a psd. I am using the .toPng() method. I would like to go from this png object to a buffer without saving to the file system. I have tried Buffer.from(png) and I have tried using Sharp's sharp(png).toBuffer() without luck. Sharp is then used to modify the png buffer.

const psd = new PSD(fileBuffer);
psd.parse();

if (!psd.image) {
    throw 'Error message';
}
const png = psd.image.toPng();
convBuffer = Buffer.from(png); 
             //await sharp(png).toBuffer() failed 
             //await png.get() failed
1

1 Answer 1

2
const { PNG } = require('pngjs');
const { PSD } = require('psd.js');
const { WritableStreamBuffer } = require('stream-buffers'); // optional, or use a raw Buffer approach
const sharp = require('sharp');

// Assume fileBuffer is already loaded with the PSD data
const psd = new PSD(fileBuffer);
psd.parse();

if (!psd.image) {
    throw new Error('PSD does not contain an image');
}

// Get the PNGJS object
const png = psd.image.toPng();

// Use PNGJS to pack the PNG stream and collect into a buffer
const getPngBuffer = () => {
    return new Promise((resolve, reject) => {
        const chunks = [];
        png.pack()
            .on('data', chunk => chunks.push(chunk))
            .on('end', () => resolve(Buffer.concat(chunks)))
            .on('error', reject);
    });
};

(async () => {
    try {
        const pngBuffer = await getPngBuffer(); // This is your usable PNG buffer

        // Now you can use Sharp with the buffer
        const modifiedImageBuffer = await sharp(pngBuffer)
            .resize(300, 300)
            .toBuffer();

        // Do whatever you need with modifiedImageBuffer...
    } catch (err) {
        console.error('Error processing image:', err);
    }
})();

Here you modify it to adjust to your needs but the idea is there

Sign up to request clarification or add additional context in comments.

1 Comment

@Taofik, thank you! That worked perfectly and PNGJS is already part of Firebase, so I didn't even need to import a new module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.