Monday, August 31, 2009

PHP GD: allow PHP to decide image type

It is at times quite troublesome having the need to detect what image type is the file, then decide which function (imagecreatefromjpeg, imagecreatefrompng or imagecreatefromgif) to use for the image. Well, here's a simple solution.

<?php

$src = "http://example.com/image.jpg";
$image = imagecreatefile($src);

function imagecreatefile($f){
$content = file_get_contents($f);
return imagecreatefromstring($content);
}

?>


That's a great and easy way. However, the bad thing is that there will be an overhead of a function and a large variable $content. Having the variable $content in the function scope allows the variable to be disposed at the end of the function, saving memory.

To fix the large variable, you can do this instead:
<?php

$src = "http://example.com/image.jpg";
$image = imagecreatefile($src);

function imagecreatefile($f){
return imagecreatefromstring(file_get_contents($f));
}

?>


Hope it helps!

No comments: