A binary column may contain empty bytes, a filename or corrupt data instead of an encoded image. Validate the BLOB before calling imagecreatefromstring(), impose size limits, and turn its warning into a controlled exception so one bad row does not corrupt the response.
Last updated: November 24, 2026.
<?php
function decodeImageBlob(string $data): GdImage
{
if ($data === '' || strlen($data) > 8 * 1024 * 1024) {
throw new InvalidArgumentException('Image data has an invalid size.');
}
$mime = (new finfo(FILEINFO_MIME_TYPE))->buffer($data);
$allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$size = getimagesizefromstring($data);
if (!in_array($mime, $allowed, true) || $size === false) {
throw new InvalidArgumentException('Unsupported image data.');
}
[$width, $height] = $size;
if ($width < 1 || $height < 1 || $width * $height > 40_000_000) {
throw new InvalidArgumentException('Image dimensions are not allowed.');
}
set_error_handler(static fn(int $level, string $message) =>
throw new RuntimeException($message));
try {
$image = imagecreatefromstring($data);
} finally {
restore_error_handler();
}
if ($image === false) {
throw new RuntimeException('The image could not be decoded.');
}
return $image;
}Tune the byte and pixel limits to available memory. The temporary error handler is always restored, so unrelated warnings keep their normal behavior.
Use each check for the right purpose
PHP documents imagecreatefromstring() as returning false for corrupt or unsupported data and raising E_WARNING for an unrecognized format. The temporary handler turns that warning into a controlled exception.
Fileinfo classifies content, while getimagesizefromstring() supplies dimensions without a temporary file. PHP’s image-size guidance cautions that dimensions alone do not prove arbitrary data is a safe image, so retain the type, byte, pixel and decode checks.
Keep bad rows out of rendered responses
Validate uploads before storage and keep the media type in a separate column. If an older BLOB mixes images with filenames or sentinel values, migrate those rows instead of guessing on every request. Never send warning text before a binary Content-Type header.
Catch the exception at the rendering boundary, log the row identifier and failure class, then return a known placeholder or HTTP 404. Do not echo the BLOB or decoder message. Release GD objects promptly after thumbnail generation.