Q: What if image is JPG or GIF?
A: When you use imagecreatefrom... methods, the image is loaded into memory as the uncompressed bitmap. there is not really a image type at this point. you can save it back out as whatever type you wish using the image... function.
Source: https://stackoverflow.com/a/7176074/3705191
But what if we wanted to Determine the Filetype of Byte String?
Before using imagecreatefromstring( $data_string )
, the actual $data_string you're providing as the argument for that function can be used to determine the image type:
$data = base64_decode($data);
// imagecreatefromstring( $data ); -- DON'T use this just yet
$f = finfo_open();
$mime_type = finfo_buffer($f, $data, FILEINFO_MIME_TYPE);
// $mime_type will hold the MIME type, e.g. image/png
Credit: https://stackoverflow.com/a/6061602/3705191
You'll have to compare the string you get with the MIME type of common image files (image/jpeg
, image/png
, image/gif
, etc.).
$im = imagecreatefromstirng( $data );
if( $mime_type == "image/png" )
imagepng( $im, "/path/where/you/want/save/the/png.png" );
if( $mime_type == "image/jpeg" )
imagejpeg( $im, "/path/where/you/want/save/the/jpg_image.jpg" );
// ...
Check this List of Common MIME Types for reference.