Created
January 15, 2015 12:09
-
-
Save dennisdegryse/fb3b158a4683159d68ce to your computer and use it in GitHub Desktop.
Getting image data from GD safely
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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