leftypol/inc/functions/metadata.php

83 lines
1.9 KiB
PHP

<?php
namespace Vichan\Functions\Metadata;
/**
* All image formats supported by vichan.
*/
const SUPPORTED_IMAGE_MIME_TYPES = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/bmp',
'image/avif'
];
/**
* Non-image file types for which only thumbnail generation is supported.
*/
const SUPPORTED_THUMB_MIME_TYPES = [
'text/plain',
'application/pdf'
];
/**
* @param string $mime Lowercase valid mime type.
* @return ?string Vichan's preferred extension for the given mime type, if any.
*/
function mime_to_ext(string $mime): ?string {
static $mime_to_ext = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/bmp' => 'bmp',
'image/avif' => 'avif',
'text/plain' => 'txt',
'application/pdf' => 'pdf'
];
return $mime_to_ext[$mime] ?? null;
}
/**
* @param string $mime Lowercase extension.
* @return ?string Vichan's preferred mime type for the given extensions, if any.
*/
function ext_to_mime(string $ext): ?string {
static $ext_to_mime = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'bmp' => 'image/bmp',
'avif' => 'image/avif',
'txt' => 'text/plain',
'pdf' => 'application/pdf'
];
return $ext_to_mime[$ext] ?? null;
}
/**
* Sniffs the image content.
*
* @param string $file_path The path to an image file.
* @return array An array with the image's width, height and mime type.
* @throws \RuntimeException On error, or on non-image files.
*/
function sniff_image(string $file_path): array {
$ret = \getimagesize($file_path);
if ($ret === false) {
throw new \RuntimeException("Could not read image sizes of '$file_path'");
}
if ($ret[2] == \IMAGETYPE_UNKNOWN) {
throw new \RuntimeException("Error '$file_path' is not an image");
}
$width = $ret[0];
$height = $ret[1];
$mime = $ret['mime'];
return [ $width, $height, $mime ];
}