Skip to content

Instantly share code, notes, and snippets.

@karlomikus
Created March 9, 2022 14:14
Show Gist options
  • Save karlomikus/e5dbbff7649d8a118471923584b084cd to your computer and use it in GitHub Desktop.
Save karlomikus/e5dbbff7649d8a118471923584b084cd to your computer and use it in GitHub Desktop.
PDF Compare with PHP and ImageMagick
<?php
declare(strict_types=1);
$controlDocument = new Imagick();
$compareDocument = new Imagick();
// Optionally control the fuzz distance
// $controlDocument->setOption('fuzz', '2%');
// Set image resolution
// $controlDocument->setResolution(100, 100);
// $compareDocument->setResolution(100, 100);
// Load documents
$controlDocument->readImage('control.pdf');
$compareDocument->readImage('compare.pdf');
// Compare images using AE metric
$result = $controlDocument->compareImages($compareDocument, Imagick::METRIC_ABSOLUTEERRORMETRIC);
// Calculate percentage
$diffPercentage = $result[1] * 100 / ($controlDocument->getImageWidth() * $controlDocument->getImageHeight());
echo "Document is " . number_format($diffPercentage, 4) . "% different.";
// Save reconstructed image
$result[0]->setImageFormat("png");
file_put_contents('test.png', $result[0]);
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment