Read Image from Buffer with pngjs

What I expect:
I'm trying to read a PNG image from a url and then parse it with pngjs

What I get:
Error: Invalid file signature

What I tried:
The result of urlToBuffer() is definitely a Buffer. I tried different encodings, tried different http clients etc.

Where the error is thrown:
Line: 48

My code:

const axios = require('axios').default; const PNG = require('pngjs').PNG; const urlToBuffer = async (url) => { return axios({ method: 'get', url: url, responseType: 'arraybuffer' }) .then(res => Buffer.from(res.data)) .then(buffer => { console.log('is buffer?', Buffer.isBuffer(buffer)); console.log(buffer); return buffer; }); }; const beforeImageURL = ' const beforeImageBuffer = await urlToBuffer(beforeImageURL); const beforeImage = PNG.sync.read(beforeImageBuffer); 

1 Answer

Your code is working very well for me, it's downloading the image and parsing it.

I've reworked a little to save the image (so I can open in an image editor / VS Code), also writing the image properties to the console.

I wonder if there is an issue with the image at the particular URL you're using for testing?

const axios = require('axios').default; const PNG = require('pngjs').PNG; const fs = require("fs"); const urlToBuffer = async (url) => { return axios({ method: 'get', url: url, responseType: 'arraybuffer' }) .then(res => Buffer.from(res.data)) .then(buffer => { console.log('is buffer?', Buffer.isBuffer(buffer)); console.log(buffer); return buffer; }); }; (async () => { const beforeImageURL = ' const beforeImageBuffer = await urlToBuffer(beforeImageURL); // Test by writing to file. fs.writeFileSync("image.png", beforeImageBuffer); const beforeImage = PNG.sync.read(beforeImageBuffer); console.log("Image properties:"); console.table( { ...beforeImage, data: [] }); })(); 

I'm using the image here to test.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like