Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is imageCreateFrom* if there is imageCreateFromString?

Tags:

php

image

gd

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

like image 975
dynamic Avatar asked Jun 09 '12 18:06

dynamic


2 Answers

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.

like image 121
Charlie Schliesser Avatar answered Sep 22 '22 15:09

Charlie Schliesser


imagecreatefromjpeg() 
imagecreatefrompng() 
imagecreatefromgif()

create image resource from a file - you pass file path as parameter and that's the only acceptable input.

imagecreatefromstring()

creates image resource from string, not file - it could be virtually anything, you can even type in a content. For example you can use

imagecreatefromstring(base64_decode('R0lGODlhAQABAJAAAP8AAAAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw=='));

to get 1x1 pixel transparent gif (useful for tracking gifs)

Granted, you could pass everything through imagecreatefromstring, but it would not be memory efficient - handling large images takes a lot of memory and with low memory limit that makes a huge difference.

like image 35
c2h5oh Avatar answered Sep 20 '22 15:09

c2h5oh