Skip to content

Commit 2159bcc

Browse files
committed
Update media type detection with GD driver
The updated method tries to use the more reliable finfo methods to detect mime type when they are available. When finfo is not installed getimagesize() or getimagesizefromstring() is used as a fallback.
1 parent 5f6d27d commit 2159bcc

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/Drivers/Gd/Decoders/AbstractDecoder.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,17 @@ abstract class AbstractDecoder extends SpecializableDecoder implements Specializ
2121
*/
2222
protected function getMediaTypeByFilePath(string $filepath): MediaType
2323
{
24+
if (function_exists('finfo_file') && function_exists('finfo_open')) {
25+
$mediaType = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
26+
if (is_string($mediaType)) {
27+
try {
28+
return MediaType::from($mediaType);
29+
} catch (ValueError) {
30+
throw new NotSupportedException('Unsupported media type (MIME) ' . $mediaType . '.');
31+
}
32+
}
33+
}
34+
2435
$info = @getimagesize($filepath);
2536

2637
if (!is_array($info)) {
@@ -42,6 +53,17 @@ protected function getMediaTypeByFilePath(string $filepath): MediaType
4253
*/
4354
protected function getMediaTypeByBinary(string $data): MediaType
4455
{
56+
if (function_exists('finfo_buffer') && function_exists('finfo_open')) {
57+
$mediaType = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $data);
58+
if (is_string($mediaType)) {
59+
try {
60+
return MediaType::from($mediaType);
61+
} catch (ValueError) {
62+
throw new NotSupportedException('Unsupported media type (MIME) ' . $mediaType . '.');
63+
}
64+
}
65+
}
66+
4567
$info = @getimagesizefromstring($data);
4668

4769
if (!is_array($info)) {

0 commit comments

Comments
 (0)