Why there is imageCreateFrom* if there is imageCreateFromString?

dynamic picture dynamic · Jun 9, 2012 · Viewed 8k times · Source

I really can't understand why GD has different function for loading images such like:

imagecreatefromjpeg() 
imagecreatefrompng() 
imagecreatefromgif()  

While there is a single function if the image is string?

imagecreatefromstring()

Indeed it's much better to read the image into the string and pass it to the function, something like:

$imgBlob = file_get_contents($imagePath);
imagecreatefromstring($imageBlob);
unset($imgBlob);  //> Free memory, but I am not interested in memory consumpation

? Or I am missing something ? This could led to potential confusion for new users

Maybe they just forgot to create a function imageCreateFromFile()?

Ps. Of course I am not interested about memory consumation using the file_get_contents method

Answer

Charlie Schliesser picture Charlie Schliesser · Dec 10, 2013

imagecreatefromstring() runs a switch against the passed image type, checks if your system has support for that image type, and then actually runs the correct imagecreatefrom* function.

You can check out the source code to see this: https://github.com/php/php-src/blob/master/ext/gd/gd.c?source=cc (line 2280 for the function, line 2301 where it switches on the image type and calls the correct function).

So, the imagecreatefromstring() function is really just a helper wrapper. You'll get a very slight benefit from not running _php_image_type (line 2217) if you call the actual image type function.