mapbox / pixelmatch

The smallest, simplest and fastest JavaScript pixel-level image comparison library
ISC License
6.1k stars 304 forks source link

Image data size does not match width/height error since release 5.0.0 #114

Closed nhoizey closed 2 years ago

nhoizey commented 2 years ago

I was using release 4.0.2 without issue, and upgrading to any of 5.x.y gives me this error:

Image data size does not match width/height

I get the images data with sharp:

const photo1Buffer = await sharp(photo1).png().raw().toBuffer();
const photo2Buffer = await sharp(photo2).png().raw().toBuffer();
const diff = pixelmatch(
  photo1Buffer,
  photo2Buffer,
  null,
  width,
  height,
  {
    threshold: 0.01,
  }
);

Your code throwing the error is:

if (img1.length !== width * height * 4) throw new Error('Image data size does not match width/height.');

It looks like you're (now?) looking for 4 values per pixel, but sharp's toBuffer returns only 3.

Did you already look for 4 values before 5.0.0?

nhoizey commented 2 years ago

Obviously, taking time to write an issue helps finding a solution… 😅

I added .ensureAlpha() in the call to sharp, and it now works:

const photo1Buffer = await sharp(photo1).ensureAlpha().raw().toBuffer();