我正在使用库“ pixelmatch”来尝试对存储为base64字符串的图像进行图像比较。他们在文档中使用pngjs创建可比较的图像。以下是我为尝试将base64字符串转换为png进行比较而编写的代码,但是我无法传递错误:
从中的“读取”功能抛出的错误:无效的文件签名
PNG.sync.read
我对这些转换不是很熟悉,并且感到困惑,因为pngjs文档说“读取”功能需要一个缓冲区,我认为这是我要传递的缓冲区。
ORDER BY
这是我为此功能编写的测试
const PNG = require('pngjs').PNG;
const pixelmatch = require('pixelmatch');
export const convertBase64ToPng = (image: string) => {
const encoding = 'base64';
const buffer = Buffer.from(image, encoding);
console.log('buffer', buffer);
PNG.sync.read(buffer);
};
export const convertToBase64 = (image: any) => Buffer.from(image).toString('base64');
export const compareToPreviousImage = (
previous: string,
current: string,
): string | boolean => {
const threshold = 0.1;
const prevPng = convertBase64ToPng(previous);
const currentPng = convertBase64ToPng(current);
const { width, height } = prevPng;
const diff = new PNG({ width, height });
const amountOfMismatchedPixels = pixelmatch(
prevPng.data,
currentPng.data,
diff.data,
width,
height,
{ threshold },
);
return amountOfMismatchedPixels > 0
&& convertToBase64(diff);
};
我敢肯定这很明显,但是任何见解都会非常有帮助,谢谢您!