Get image type from base64 encoded src string

Get image type from base64 encoded src string

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Image MIME Types from Base64 Strings

When you encounter image sources encoded as data: URLs, the file extension is often missing or unreliable. A string like data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA... contains the critical metadata right at the beginning. In PHP, extracting the specific image type (JPEG, PNG, GIF) from this format is a straightforward string manipulation task that relies on understanding the structure of the URI scheme.

The data: URL format follows a strict syntax defined by RFC 2397. The general pattern is data:[<mediatype>][;base64],<data>. The MIME type, which explicitly states the file format like image/jpeg or image/png, sits between the initial data: prefix and the optional ;base64 separator.

To isolate this part in PHP, you need to locate the comma that separates the header from the actual binary data. The most robust approach uses the native explode() function with a limit parameter. This prevents issues if your base64 string contains commas (which is rare but theoretically possible in specific padding scenarios or custom headers).

Here is a practical implementation:

function getImageTypeFromBase64($srcString) {
    // Ensure we are dealing with a string and not null
    if (!is_string($srcString)) {
        return null;
    }

    // Explode the string at the first comma found
    $parts = explode(',', $srcString, 2);

    // If there is no comma, it's not a valid data URL
    if (count($parts) !== 2) {
        return null;
    }

    $header = trim($parts[0]);

    // The header format is always: mediaType;base64 or just mediaType
    // We split by the semicolon to get the media type
    $segments = explode(';', $header);

    return $segments[0]; // Returns 'image/jpeg', 'image/png', etc.
}

You can then strip the image/ prefix if you strictly need just the extension-like identifier:

$imageType = getImageTypeFromBase64($srcString);
$extension = str_replace('image/', '', $imageType); // Result: 'jpeg' or 'png'

This method is superior to using regular expressions for simple extraction because it relies on structural guarantees rather than pattern matching. Regular expressions can be brittle; if the URL structure ever evolves slightly, a regex might fail silently or produce incorrect matches. The explode approach is explicit and easy to debug.

Handling Edge Cases

While JPEG, PNG, and GIF are common, developers must remember that not all MIME types map strictly to file extensions. For instance, SVG images use image/svg+xml. If your application expects a specific set of file extensions for storage logic, you need a mapping strategy. The raw MIME type returned by the extraction is more accurate than guessing based on the first few bytes of the base64 data, though byte analysis is an alternative if the header is missing or malformed.

Another consideration is security. If this function runs in an environment where user input dictates storage paths (e.g., saving uploaded files), relying solely on the extracted type from a data: URL passed via GET parameters can be risky. Attackers might attempt to manipulate headers, though valid data URLs are strictly formatted. It is generally safer to validate the resulting MIME type against a whitelist of allowed types before processing the file further.

If you are working within the Laravel ecosystem, this logic often fits into validation middleware or image processing pipelines. When using libraries like Intervention/Image or native PHP GD functions, passing a base64 string directly usually works, but knowing the exact type beforehand helps in selecting the correct output format or compression settings. For more complex image handling needs in Laravel, you might consider integrating with services from https://laravelcompany.com that offer managed media storage solutions, though understanding the raw data URL structure remains essential for client-side interactions.

Our network