Home  >  Article  >  Backend Development  >  How to Determine Image Type from Base64 String in PHP?

How to Determine Image Type from Base64 String in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 03:56:02837browse

How to Determine Image Type from Base64 String in PHP?

Determine Image Type from Base64 String in PHP

Is it feasible to ascertain the file type of an image encoded as a base64 string in PHP? Unfortunately, solely possessing the encoded string presents a challenge in acquiring the image's original file type. To decipher the image type, one might utilize the imagecreatefromstring() function, which generates an image resource. However, this resource possesses a specialized representation in PHP, obscuring the original image type.

Fortunately, the PHP FileInfo extension offers a solution. This extension provides a straightforward method to determine the file type of binary data, including base64-encoded strings. Here's how it works:

<code class="php">$encoded_string = "....";
$imgdata = base64_decode($encoded_string);

$f = finfo_open();

$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);</code>

This code snippet decodes the base64-encoded string, opens a FileInfo resource, and obtains the file type using the finfo_buffer() function. The resulting $mime_type variable will contain the file type, such as "image/jpeg" or "image/png". With this information, you can determine the original file type without needing to know it beforehand and can save the image as the appropriate file type.

The above is the detailed content of How to Determine Image Type from Base64 String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn