comparison_copy( self::COMPARE_EDGE ); $metric = $this->choose_metric( $reference ); if ( null === $metric ) { return null; } $format = 'image/jpeg' === $mime ? 'JPEG' : 'WEBP'; if ( $this->score( $reference, $format, $max_quality, $metric ) < $target ) { $reference->clear(); return $max_quality; } $low = self::MIN_QUALITY; $high = $max_quality; $best = $max_quality; while ( $low <= $high ) { $quality = (int) floor( ( $low + $high ) / 2 ); if ( $this->score( $reference, $format, $quality, $metric ) >= $target ) { $best = $quality; $high = $quality - 1; } else { $low = $quality + 1; } } $reference->clear(); return $best; } catch ( Throwable $e ) { return null; } } /** * Picks a metric, learning from a self-comparison whether it reports similarity or error. * * ImageMagick versions disagree on whether identical images score 1 or 0 under SSIM. * * @param Imagick $reference Reference image. * @return array{id: int<1, 12>, inverted: bool}|null */ private function choose_metric( Imagick $reference ): ?array { $candidates = array(); if ( defined( 'Imagick::METRIC_STRUCTURAL_SIMILARITY_ERROR' ) ) { $candidates[] = (int) constant( 'Imagick::METRIC_STRUCTURAL_SIMILARITY_ERROR' ); } if ( defined( 'Imagick::METRIC_ROOTMEANSQUAREDERROR' ) ) { $candidates[] = (int) constant( 'Imagick::METRIC_ROOTMEANSQUAREDERROR' ); } foreach ( $candidates as $metric ) { try { $compared = $reference->compareImages( $reference, $metric ); $self = (float) $compared[1]; $compared[0]->clear(); } catch ( Throwable $e ) { continue; } if ( abs( $self - 1.0 ) < 0.001 ) { return array( 'id' => $metric, 'inverted' => false, ); } if ( abs( $self ) < 0.001 ) { return array( 'id' => $metric, 'inverted' => true, ); } } return null; } /** * Encodes the reference at a quality and scores the decoded result. * * @param Imagick $reference Reference image. * @param string $format Imagick format name. * @param int $quality Quality to test. * @param array{id: int<1, 12>, inverted: bool} $metric Metric to use. * @return float Similarity, where 1 is identical. */ private function score( Imagick $reference, string $format, int $quality, array $metric ): float { $candidate = $reference->getImage(); $candidate->setImageFormat( $format ); $candidate->setImageCompressionQuality( $quality ); $blob = $candidate->getImageBlob(); $candidate->clear(); $decoded = new Imagick(); $decoded->readImageBlob( $blob ); $compared = $reference->compareImages( $decoded, $metric['id'] ); $value = (float) $compared[1]; $compared[0]->clear(); $decoded->clear(); return $metric['inverted'] ? 1.0 - $value : $value; } }