4 * @task enormous Detecting Enormous Images
5 * @task save Saving Image Data
7 final class PhabricatorImageTransformer
extends Phobject
{
10 /* -( Saving Image Data )-------------------------------------------------- */
14 * Save an image resource to a string representation suitable for storage or
15 * transmission as an image file.
17 * Optionally, you can specify a preferred MIME type like `"image/png"`.
18 * Generally, you should specify the MIME type of the original file if you're
19 * applying file transformations. The MIME type may not be honored if
20 * Phabricator can not encode images in the given format (based on available
21 * extensions), but can save images in another format.
23 * @param resource GD image resource.
24 * @param string? Optionally, preferred mime type.
25 * @return string Bytes of an image file.
28 public static function saveImageDataInAnyFormat($data, $preferred_mime = '') {
30 switch ($preferred_mime) {
32 $preferred = self
::saveImageDataAsGIF($data);
35 $preferred = self
::saveImageDataAsPNG($data);
39 if ($preferred !== null) {
43 $data = self
::saveImageDataAsJPG($data);
48 $data = self
::saveImageDataAsPNG($data);
53 $data = self
::saveImageDataAsGIF($data);
58 throw new Exception(pht('Failed to save image data into any format.'));
63 * Save an image in PNG format, returning the file data as a string.
65 * @param resource GD image resource.
66 * @return string|null PNG file as a string, or null on failure.
69 private static function saveImageDataAsPNG($image) {
70 if (!function_exists('imagepng')) {
74 // NOTE: Empirically, the highest compression level (9) seems to take
75 // up to twice as long as the default compression level (6) but produce
76 // only slightly smaller files (10% on avatars, 3% on screenshots).
79 $result = imagepng($image, null, 6);
80 $output = ob_get_clean();
91 * Save an image in GIF format, returning the file data as a string.
93 * @param resource GD image resource.
94 * @return string|null GIF file as a string, or null on failure.
97 private static function saveImageDataAsGIF($image) {
98 if (!function_exists('imagegif')) {
103 $result = imagegif($image);
104 $output = ob_get_clean();
115 * Save an image in JPG format, returning the file data as a string.
117 * @param resource GD image resource.
118 * @return string|null JPG file as a string, or null on failure.
121 private static function saveImageDataAsJPG($image) {
122 if (!function_exists('imagejpeg')) {
127 $result = imagejpeg($image);
128 $output = ob_get_clean();