is there a way to use imagecreatefromstring()
and get somehow what is the image type?
Asked
Active
Viewed 2,559 times
7

Michael Berkowski
- 267,341
- 46
- 444
- 390

Marcin
- 5,469
- 15
- 55
- 69
2 Answers
3
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.
$img = imagecreatefromstring($data);
imagepng($img, "file path and name");
imagedestroy($img);
http://us2.php.net/manual/en/function.imagecreatefromstring.php

Bueller
- 2,336
- 17
- 11
-
ok, but from the detection onload point of view there is nothing like that ? – Marcin Aug 24 '11 at 13:23
-
what is the end goal you are trying to achieve? Do you wish to determing that what you have loaded is actually an image or do you really need to know the exact type of image being loaded? – Bueller Aug 24 '11 at 15:22
0
Before using imagecreatefromstring( $string )
, the actual $string you're providing as the argument for that function can be used to determine the image type:
$imgstring = "...";
// imagecreatefromstring( $imgstring ); -- DON'T use this just yet
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgstring, 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.).
$img = imagecreatefromstirng( $imgstring );
if( $mime_type == "image/png" )
imagepng( $img, $filepath_to_save_to );
if( $mime_type == "image/jpeg" )
imagejpeg( $img, $filepath_to_save_to );
// ...
Check this List of Common MIME Types for reference.

Prid
- 1,272
- 16
- 20
-
**Beware:** this *may* return the generic `application/octet-stream` MIME type if it fails to determine the correct type of image. This can happen when the byte stream holds incomplete information (https://stackoverflow.com/a/66750339/3705191). That's why I'm not sure how reliable this is. Someone suggests to save the file somewhere first and then using e.g. `finfo_open` as a more reliable approach: https://www.php.net/manual/en/function.finfo-buffer.php#Hcom118313 – Prid Jan 25 '23 at 23:55