Skip to content

Commit

Permalink
Reintroduce ::assertImageEquals()
Browse files Browse the repository at this point in the history
  • Loading branch information
cmb69 committed Mar 22, 2023
1 parent 21ada95 commit a31eff9
Showing 1 changed file with 68 additions and 3 deletions.
71 changes: 68 additions & 3 deletions tests/VisualCaptchaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ public function testCreateImage()
{
$sut = new FakeVisualCaptcha(vfsStream::url('test/images/'), '../cryptographp/fonts', self::CONFIG);
$actual = $sut->createImage('ABCD');
ob_start();
imagegif($actual);
Approvals::verifyStringWithFileExtension(ob_get_clean(), "gif");
$this->assertImageEquals('image', $actual);
}

public function testCreateErrorImage()
Expand Down Expand Up @@ -203,4 +201,71 @@ public function testWordwrapInErrorImage()
imagegif($actual);
Approvals::verifyStringWithFileExtension(ob_get_clean(), "gif");
}

/**
* @param string $expected
* @param resource $actual
* @return void
*/
private function assertImageEquals($expected, $actual)
{
$im1 = imagecreatefrompng(__DIR__ . "/images/$expected.png");
$im2 = $actual;

$w1 = imagesx($im1);
$h1 = imagesy($im1);

$w2 = imagesx($im2);
$h2 = imagesy($im2);

if ($w1 !== $w2 || $h1 !== $h2) {
$this->assertTrue(false);
}

$im3 = imagecreatetruecolor($w1, $h1);
imagealphablending($im3, false);

$difference = 0.0;
for ($i = 0; $i < $w1; $i++) {
for ($j = 0; $j < $h1; $j++) {
$c1 = imagecolorat($im1, $i, $j);
$c2 = imagecolorat($im2, $i, $j);

$a1 = ($c1 >> 24) & 0x7f;
$r1 = ($c1 >> 16) & 0xff;
$g1 = ($c1 >> 8) & 0xff;
$b1 = ($c1 >> 0) & 0xff;

$a2 = ($c2 >> 24) & 0x7f;
$r2 = ($c2 >> 16) & 0xff;
$g2 = ($c2 >> 8) & 0xff;
$b2 = ($c2 >> 0) & 0xff;

if ($a1 !== 0 || $a2 !== 0) {
$this->assertTrue(false);
}

$d = sqrt(($r1 - $r2)**2 + ($g1 - $g2)**2 + ($b1 - $b2)**2) / sqrt(3 * 255**2);
$difference += $d;

$a3 = 127 - (int) (127 * $d);
$r3 = (int) (sqrt($r1**2 + $r2**2) / sqrt(2 * 255**2) * 255);
$g3 = (int) (sqrt($g1**2 + $g2**2) / sqrt(2 * 255**2) * 255);
$b3 = (int) (sqrt($b1**2 + $b2**2) / sqrt(2 * 255**2) * 255);

$c3 = ($a3 << 24) | ($r3 << 16) | ($g3 << 8) | $b3;

imagesetpixel($im3, $i, $j, $c3);
}
}

if ($difference > 0.0) {
imagesavealpha($im2, true);
imagepng($im2, __DIR__ . "/images/$expected.out.png");
imagesavealpha($im3, true);
imagepng($im3, __DIR__ . "/images/$expected.diff.png");
}

return $this->assertEqualsWithDelta(0.0, $difference, 0.1);
}
}

0 comments on commit a31eff9

Please sign in to comment.