Skip to content

Instantly share code, notes, and snippets.

@dennisdegryse
Created January 15, 2015 12:09
Show Gist options
  • Select an option

  • Save dennisdegryse/fb3b158a4683159d68ce to your computer and use it in GitHub Desktop.

Select an option

Save dennisdegryse/fb3b158a4683159d68ce to your computer and use it in GitHub Desktop.
Getting image data from GD safely
<?php
/**
* Gets the image data from a GD image resource.
*
* @param resource $image The image resource.
* @param string $format The image format.
*
* @throws Exception When an illegal format was specified.
*
* @return string The image data as a string.
*
* @author Dennis Degryse
*/
imagedata($image, $format) {
$valid_formats = ['jpeg', 'gif', 'png', 'bmp', 'wbmp', 'webp', 'xbm'];
if (!in_array($format, $valid_formats)) {
throw new \Exception("Invalid image format '$format' specified.");
}
// first create a back-up of your current OB content
$ob_backup = ob_get_contents();
if ($ob_backup !== false) {
ob_end_clean();
}
// restart the OB and output the image data in it
ob_start();
call_user_func("image$format", $image);
// catch the contents of the OB and clear it
$image_data = ob_get_contents();
ob_end_clean();
// restore the previous state of the OB
if ($ob_backup !== false) {
ob_start();
print($ob_backup);
}
return $image_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment