image.gd.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. /**
  3. * @file
  4. * GD2 toolkit for image manipulation within Drupal.
  5. */
  6. /**
  7. * @addtogroup image
  8. * @{
  9. */
  10. /**
  11. * Retrieve settings for the GD2 toolkit.
  12. */
  13. function image_gd_settings() {
  14. if (image_gd_check_settings()) {
  15. $form['status'] = array(
  16. '#markup' => t('The GD toolkit is installed and working properly.')
  17. );
  18. $form['image_jpeg_quality'] = array(
  19. '#type' => 'textfield',
  20. '#title' => t('JPEG quality'),
  21. '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality but bigger files.'),
  22. '#size' => 10,
  23. '#maxlength' => 3,
  24. '#default_value' => variable_get('image_jpeg_quality', 75),
  25. '#field_suffix' => t('%'),
  26. );
  27. $form['#element_validate'] = array('image_gd_settings_validate');
  28. return $form;
  29. }
  30. else {
  31. form_set_error('image_toolkit', t('The GD image toolkit requires that the GD module for PHP be installed and configured properly. For more information see <a href="@url">PHP\'s image documentation</a>.', array('@url' => 'http://php.net/image')));
  32. return FALSE;
  33. }
  34. }
  35. /**
  36. * Validate the submitted GD settings.
  37. */
  38. function image_gd_settings_validate($form, &$form_state) {
  39. // Validate image quality range.
  40. $value = $form_state['values']['image_jpeg_quality'];
  41. if (!is_numeric($value) || $value < 0 || $value > 100) {
  42. form_set_error('image_jpeg_quality', t('JPEG quality must be a number between 0 and 100.'));
  43. }
  44. }
  45. /**
  46. * Verify GD2 settings (that the right version is actually installed).
  47. *
  48. * @return
  49. * A boolean indicating if the GD toolkit is available on this machine.
  50. */
  51. function image_gd_check_settings() {
  52. // GD2 support is available.
  53. return function_exists('imagegd2');
  54. }
  55. /**
  56. * Scale an image to the specified size using GD.
  57. *
  58. * @param $image
  59. * An image object. The $image->resource, $image->info['width'], and
  60. * $image->info['height'] values will be modified by this call.
  61. * @param $width
  62. * The new width of the resized image, in pixels.
  63. * @param $height
  64. * The new height of the resized image, in pixels.
  65. * @return
  66. * TRUE or FALSE, based on success.
  67. *
  68. * @see image_resize()
  69. */
  70. function image_gd_resize(stdClass $image, $width, $height) {
  71. $res = image_gd_create_tmp($image, $width, $height);
  72. if (!imagecopyresampled($res, $image->resource, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) {
  73. return FALSE;
  74. }
  75. imagedestroy($image->resource);
  76. // Update image object.
  77. $image->resource = $res;
  78. $image->info['width'] = $width;
  79. $image->info['height'] = $height;
  80. return TRUE;
  81. }
  82. /**
  83. * Rotate an image the given number of degrees.
  84. *
  85. * @param $image
  86. * An image object. The $image->resource, $image->info['width'], and
  87. * $image->info['height'] values will be modified by this call.
  88. * @param $degrees
  89. * The number of (clockwise) degrees to rotate the image.
  90. * @param $background
  91. * An hexadecimal integer specifying the background color to use for the
  92. * uncovered area of the image after the rotation. E.g. 0x000000 for black,
  93. * 0xff00ff for magenta, and 0xffffff for white. For images that support
  94. * transparency, this will default to transparent. Otherwise it will
  95. * be white.
  96. * @return
  97. * TRUE or FALSE, based on success.
  98. *
  99. * @see image_rotate()
  100. */
  101. function image_gd_rotate(stdClass $image, $degrees, $background = NULL) {
  102. // PHP installations using non-bundled GD do not have imagerotate.
  103. if (!function_exists('imagerotate')) {
  104. watchdog('image', 'The image %file could not be rotated because the imagerotate() function is not available in this PHP installation.', array('%file' => $image->source));
  105. return FALSE;
  106. }
  107. // PHP 5.5 GD bug: https://bugs.php.net/bug.php?id=65148: To prevent buggy
  108. // behavior on negative multiples of 90 degrees we convert any negative
  109. // angle to a positive one between 0 and 360 degrees.
  110. $degrees -= floor($degrees / 360) * 360;
  111. // Convert the hexadecimal background value to a RGBA array.
  112. if (isset($background)) {
  113. $background = array(
  114. 'red' => $background >> 16 & 0xFF,
  115. 'green' => $background >> 8 & 0xFF,
  116. 'blue' => $background & 0xFF,
  117. 'alpha' => 0,
  118. );
  119. }
  120. else {
  121. // Background color is not specified: use transparent white as background.
  122. $background = array(
  123. 'red' => 255,
  124. 'green' => 255,
  125. 'blue' => 255,
  126. 'alpha' => 127
  127. );
  128. }
  129. // Store the color index for the background as that is what GD uses.
  130. $background_idx = imagecolorallocatealpha($image->resource, $background['red'], $background['green'], $background['blue'], $background['alpha']);
  131. // Images are assigned a new color palette when rotating, removing any
  132. // transparency flags. For GIF images, keep a record of the transparent color.
  133. if ($image->info['extension'] == 'gif') {
  134. // GIF does not work with a transparency channel, but can define 1 color
  135. // in its palette to act as transparent.
  136. // Get the current transparent color, if any.
  137. $gif_transparent_id = imagecolortransparent($image->resource);
  138. if ($gif_transparent_id !== -1) {
  139. // The gif already has a transparent color set: remember it to set it on
  140. // the rotated image as well.
  141. $transparent_gif_color = imagecolorsforindex($image->resource, $gif_transparent_id);
  142. if ($background['alpha'] >= 127) {
  143. // We want a transparent background: use the color already set to act
  144. // as transparent, as background.
  145. $background_idx = $gif_transparent_id;
  146. }
  147. }
  148. else {
  149. // The gif does not currently have a transparent color set.
  150. if ($background['alpha'] >= 127) {
  151. // But as the background is transparent, it should get one.
  152. $transparent_gif_color = $background;
  153. }
  154. }
  155. }
  156. $image->resource = imagerotate($image->resource, 360 - $degrees, $background_idx);
  157. // GIFs need to reassign the transparent color after performing the rotate.
  158. if (isset($transparent_gif_color)) {
  159. $background = imagecolorexactalpha($image->resource, $transparent_gif_color['red'], $transparent_gif_color['green'], $transparent_gif_color['blue'], $transparent_gif_color['alpha']);
  160. imagecolortransparent($image->resource, $background);
  161. }
  162. $image->info['width'] = imagesx($image->resource);
  163. $image->info['height'] = imagesy($image->resource);
  164. return TRUE;
  165. }
  166. /**
  167. * Crop an image using the GD toolkit.
  168. *
  169. * @param $image
  170. * An image object. The $image->resource, $image->info['width'], and
  171. * $image->info['height'] values will be modified by this call.
  172. * @param $x
  173. * The starting x offset at which to start the crop, in pixels.
  174. * @param $y
  175. * The starting y offset at which to start the crop, in pixels.
  176. * @param $width
  177. * The width of the cropped area, in pixels.
  178. * @param $height
  179. * The height of the cropped area, in pixels.
  180. * @return
  181. * TRUE or FALSE, based on success.
  182. *
  183. * @see image_crop()
  184. */
  185. function image_gd_crop(stdClass $image, $x, $y, $width, $height) {
  186. $res = image_gd_create_tmp($image, $width, $height);
  187. if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) {
  188. return FALSE;
  189. }
  190. // Destroy the original image and return the modified image.
  191. imagedestroy($image->resource);
  192. $image->resource = $res;
  193. $image->info['width'] = $width;
  194. $image->info['height'] = $height;
  195. return TRUE;
  196. }
  197. /**
  198. * Convert an image resource to grayscale.
  199. *
  200. * Note that transparent GIFs loose transparency when desaturated.
  201. *
  202. * @param $image
  203. * An image object. The $image->resource value will be modified by this call.
  204. * @return
  205. * TRUE or FALSE, based on success.
  206. *
  207. * @see image_desaturate()
  208. */
  209. function image_gd_desaturate(stdClass $image) {
  210. // PHP installations using non-bundled GD do not have imagefilter.
  211. if (!function_exists('imagefilter')) {
  212. watchdog('image', 'The image %file could not be desaturated because the imagefilter() function is not available in this PHP installation.', array('%file' => $image->source));
  213. return FALSE;
  214. }
  215. return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);
  216. }
  217. /**
  218. * GD helper function to create an image resource from a file.
  219. *
  220. * @param $image
  221. * An image object. The $image->resource value will populated by this call.
  222. * @return
  223. * TRUE or FALSE, based on success.
  224. *
  225. * @see image_load()
  226. */
  227. function image_gd_load(stdClass $image) {
  228. $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  229. $function = 'imagecreatefrom' . $extension;
  230. if (function_exists($function) && $image->resource = $function($image->source)) {
  231. if (imageistruecolor($image->resource)) {
  232. return TRUE;
  233. }
  234. else {
  235. // Convert indexed images to truecolor, copying the image to a new
  236. // truecolor resource, so that filters work correctly and don't result
  237. // in unnecessary dither.
  238. $resource = image_gd_create_tmp($image, $image->info['width'], $image->info['height']);
  239. if ($resource) {
  240. imagecopy($resource, $image->resource, 0, 0, 0, 0, imagesx($resource), imagesy($resource));
  241. imagedestroy($image->resource);
  242. $image->resource = $resource;
  243. }
  244. }
  245. return (bool) $image->resource;
  246. }
  247. return FALSE;
  248. }
  249. /**
  250. * GD helper to write an image resource to a destination file.
  251. *
  252. * @param $image
  253. * An image object.
  254. * @param $destination
  255. * A string file URI or path where the image should be saved.
  256. * @return
  257. * TRUE or FALSE, based on success.
  258. *
  259. * @see image_save()
  260. */
  261. function image_gd_save(stdClass $image, $destination) {
  262. $scheme = file_uri_scheme($destination);
  263. // Work around lack of stream wrapper support in imagejpeg() and imagepng().
  264. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  265. // If destination is not local, save image to temporary local file.
  266. $local_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
  267. if (!isset($local_wrappers[$scheme])) {
  268. $permanent_destination = $destination;
  269. $destination = drupal_tempnam('temporary://', 'gd_');
  270. }
  271. // Convert stream wrapper URI to normal path.
  272. $destination = drupal_realpath($destination);
  273. }
  274. $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  275. $function = 'image' . $extension;
  276. if (!function_exists($function)) {
  277. return FALSE;
  278. }
  279. if ($extension == 'jpeg') {
  280. $success = $function($image->resource, $destination, variable_get('image_jpeg_quality', 75));
  281. }
  282. else {
  283. // Always save PNG images with full transparency.
  284. if ($extension == 'png') {
  285. imagealphablending($image->resource, FALSE);
  286. imagesavealpha($image->resource, TRUE);
  287. }
  288. $success = $function($image->resource, $destination);
  289. }
  290. // Move temporary local file to remote destination.
  291. if (isset($permanent_destination) && $success) {
  292. return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
  293. }
  294. return $success;
  295. }
  296. /**
  297. * Create a truecolor image preserving transparency from a provided image.
  298. *
  299. * @param $image
  300. * An image object.
  301. * @param $width
  302. * The new width of the new image, in pixels.
  303. * @param $height
  304. * The new height of the new image, in pixels.
  305. * @return
  306. * A GD image handle.
  307. */
  308. function image_gd_create_tmp(stdClass $image, $width, $height) {
  309. $res = imagecreatetruecolor($width, $height);
  310. if ($image->info['extension'] == 'gif') {
  311. // Find out if a transparent color is set, will return -1 if no
  312. // transparent color has been defined in the image.
  313. $transparent = imagecolortransparent($image->resource);
  314. if ($transparent >= 0) {
  315. // Find out the number of colors in the image palette. It will be 0 for
  316. // truecolor images.
  317. $palette_size = imagecolorstotal($image->resource);
  318. if ($palette_size == 0 || $transparent < $palette_size) {
  319. // Set the transparent color in the new resource, either if it is a
  320. // truecolor image or if the transparent color is part of the palette.
  321. // Since the index of the transparency color is a property of the
  322. // image rather than of the palette, it is possible that an image
  323. // could be created with this index set outside the palette size (see
  324. // http://stackoverflow.com/a/3898007).
  325. $transparent_color = imagecolorsforindex($image->resource, $transparent);
  326. $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
  327. // Flood with our new transparent color.
  328. imagefill($res, 0, 0, $transparent);
  329. imagecolortransparent($res, $transparent);
  330. }
  331. else {
  332. imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
  333. }
  334. }
  335. }
  336. elseif ($image->info['extension'] == 'png') {
  337. imagealphablending($res, FALSE);
  338. $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
  339. imagefill($res, 0, 0, $transparency);
  340. imagealphablending($res, TRUE);
  341. imagesavealpha($res, TRUE);
  342. }
  343. else {
  344. imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
  345. }
  346. return $res;
  347. }
  348. /**
  349. * Get details about an image.
  350. *
  351. * @param $image
  352. * An image object.
  353. * @return
  354. * FALSE, if the file could not be found or is not an image. Otherwise, a
  355. * keyed array containing information about the image:
  356. * - "width": Width, in pixels.
  357. * - "height": Height, in pixels.
  358. * - "extension": Commonly used file extension for the image.
  359. * - "mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
  360. *
  361. * @see image_get_info()
  362. */
  363. function image_gd_get_info(stdClass $image) {
  364. $details = FALSE;
  365. $data = @getimagesize($image->source);
  366. if (isset($data) && is_array($data)) {
  367. $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
  368. $extension = isset($extensions[$data[2]]) ? $extensions[$data[2]] : '';
  369. $details = array(
  370. 'width' => $data[0],
  371. 'height' => $data[1],
  372. 'extension' => $extension,
  373. 'mime_type' => $data['mime'],
  374. );
  375. }
  376. return $details;
  377. }
  378. /**
  379. * @} End of "addtogroup image".
  380. */