From 2ee997d98fd08a5a4a54adc5bf0726bc2b563e12 Mon Sep 17 00:00:00 2001 From: Oliver Vogel Date: Sat, 3 Aug 2024 11:04:30 +0200 Subject: [PATCH] Add method to detect PNG color types --- tests/Traits/CanInspectPngFormat.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/Traits/CanInspectPngFormat.php b/tests/Traits/CanInspectPngFormat.php index 510466f7..c09a4f7f 100644 --- a/tests/Traits/CanInspectPngFormat.php +++ b/tests/Traits/CanInspectPngFormat.php @@ -24,4 +24,29 @@ private function isInterlacedPng(string $imagedata): bool return ord($contents[28]) != 0; } + + /** + * Try to detect PNG color type from given binary data + * + * @param string $data + * @return string + */ + private function pngColorType(string $data): string + { + if (substr($data, 1, 3) !== 'PNG') { + return 'unkown'; + } + + $pos = strpos($data, 'IHDR'); + $type = substr($data, $pos + 13, 1); + + return match (unpack('C', $type)[1]) { + 0 => 'grayscale', + 2 => 'truecolor', + 3 => 'indexed', + 4 => 'grayscale-alpha', + 6 => 'truecolor-alpha', + default => 'unknown', + }; + } }