Read Image from Buffer with pngjs

2.6k Views Asked by At

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:
https://github.com/lukeapage/pngjs/blob/master/lib/parser.js 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 = 'https://my-source.com/image.png';
const beforeImageBuffer = await urlToBuffer(beforeImageURL);
const beforeImage = PNG.sync.read(beforeImageBuffer);
1

There are 1 best solutions below

1
On

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 = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
    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.