- if (is_null($type)) {
- // Guessing from extension? Isn't that... dangerous?
- if (class_exists('Imagick') && file_exists($filename) && is_readable($filename)) {
- /**
- * Well, this not much better,
- * but at least it comes from the data inside the image,
- * we won't be tricked by a manipulated extension
- */
- $image = new Imagick($filename);
- $type = $image->getImageMimeType();
- } else {
- $ext = pathinfo($filename, PATHINFO_EXTENSION);
- $types = self::supportedTypes();
- $type = 'image/jpeg';
- foreach ($types as $m => $e) {
- if ($ext == $e) {
- $type = $m;
- }
- }
+ return self::guessTypeByExtension($filename);
+ }
+
+ /**
+ * Fetch image mimetype from the image data or guessing from the file name
+ *
+ * @param string $sourcefile Source file of the image
+ * @param string $filename File name (for guessing the type via the extension)
+ * @param string $mime default mime type
+ *
+ * @return string
+ * @throws \Exception
+ */
+ public static function getMimeTypeBySource(string $sourcefile, string $filename = '', string $mime = '')
+ {
+ if (substr($mime, 0, 6) == 'image/') {
+ Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $mime]);
+ return $mime;
+ }
+
+ $image = @getimagesize($sourcefile);
+ if (!empty($image['mime'])) {
+ Logger::info('Mime type detected via file', ['filename' => $filename, 'default' => $mime, 'image' => $image]);
+ return $image['mime'];
+ }
+
+ return self::guessTypeByExtension($filename);
+ }
+
+ /**
+ * Guess image mimetype from the filename
+ *
+ * @param string $filename Image filename
+ *
+ * @return string
+ * @throws \Exception
+ */
+ public static function guessTypeByExtension(string $filename)
+ {
+ $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION);
+ $types = self::supportedTypes();
+ $type = 'image/jpeg';
+ foreach ($types as $m => $e) {
+ if ($ext == $e) {
+ $type = $m;