image.gd.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. $width = (int) $width;
  187. $height = (int) $height;
  188. $res = image_gd_create_tmp($image, $width, $height);
  189. if (!imagecopyresampled($res, $image->resource, 0, 0, (int) $x, (int) $y, $width, $height, $width, $height)) {
  190. return FALSE;
  191. }
  192. // Destroy the original image and return the modified image.
  193. imagedestroy($image->resource);
  194. $image->resource = $res;
  195. $image->info['width'] = $width;
  196. $image->info['height'] = $height;
  197. return TRUE;
  198. }
  199. /**
  200. * Convert an image resource to grayscale.
  201. *
  202. * Note that transparent GIFs loose transparency when desaturated.
  203. *
  204. * @param $image
  205. * An image object. The $image->resource value will be modified by this call.
  206. * @return
  207. * TRUE or FALSE, based on success.
  208. *
  209. * @see image_desaturate()
  210. */
  211. function image_gd_desaturate(stdClass $image) {
  212. // PHP installations using non-bundled GD do not have imagefilter.
  213. if (!function_exists('imagefilter')) {
  214. watchdog('image', 'The image %file could not be desaturated because the imagefilter() function is not available in this PHP installation.', array('%file' => $image->source));
  215. return FALSE;
  216. }
  217. return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);
  218. }
  219. /**
  220. * GD helper function to create an image resource from a file.
  221. *
  222. * @param $image
  223. * An image object. The $image->resource value will populated by this call.
  224. * @return
  225. * TRUE or FALSE, based on success.
  226. *
  227. * @see image_load()
  228. */
  229. function image_gd_load(stdClass $image) {
  230. $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  231. $function = 'imagecreatefrom' . $extension;
  232. if (function_exists($function) && $image->resource = $function($image->source)) {
  233. if (imageistruecolor($image->resource)) {
  234. return TRUE;
  235. }
  236. else {
  237. // Convert indexed images to truecolor, copying the image to a new
  238. // truecolor resource, so that filters work correctly and don't result
  239. // in unnecessary dither.
  240. $resource = image_gd_create_tmp($image, $image->info['width'], $image->info['height']);
  241. if ($resource) {
  242. imagecopy($resource, $image->resource, 0, 0, 0, 0, imagesx($resource), imagesy($resource));
  243. imagedestroy($image->resource);
  244. $image->resource = $resource;
  245. }
  246. }
  247. return (bool) $image->resource;
  248. }
  249. return FALSE;
  250. }
  251. /**
  252. * GD helper to write an image resource to a destination file.
  253. *
  254. * @param $image
  255. * An image object.
  256. * @param $destination
  257. * A string file URI or path where the image should be saved.
  258. * @return
  259. * TRUE or FALSE, based on success.
  260. *
  261. * @see image_save()
  262. */
  263. function image_gd_save(stdClass $image, $destination) {
  264. $scheme = file_uri_scheme($destination);
  265. // Work around lack of stream wrapper support in imagejpeg() and imagepng().
  266. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  267. // If destination is not local, save image to temporary local file.
  268. $local_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
  269. if (!isset($local_wrappers[$scheme])) {
  270. $permanent_destination = $destination;
  271. $destination = drupal_tempnam('temporary://', 'gd_');
  272. }
  273. // Convert stream wrapper URI to normal path.
  274. $destination = drupal_realpath($destination);
  275. }
  276. $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  277. $function = 'image' . $extension;
  278. if (!function_exists($function)) {
  279. return FALSE;
  280. }
  281. if ($extension == 'jpeg') {
  282. $success = $function($image->resource, $destination, variable_get('image_jpeg_quality', 75));
  283. }
  284. else {
  285. // Always save PNG images with full transparency.
  286. if ($extension == 'png') {
  287. imagealphablending($image->resource, FALSE);
  288. imagesavealpha($image->resource, TRUE);
  289. }
  290. $success = $function($image->resource, $destination);
  291. }
  292. // Move temporary local file to remote destination.
  293. if (isset($permanent_destination) && $success) {
  294. return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
  295. }
  296. return $success;
  297. }
  298. /**
  299. * Create a truecolor image preserving transparency from a provided image.
  300. *
  301. * @param $image
  302. * An image object.
  303. * @param $width
  304. * The new width of the new image, in pixels.
  305. * @param $height
  306. * The new height of the new image, in pixels.
  307. * @return
  308. * A GD image handle.
  309. */
  310. function image_gd_create_tmp(stdClass $image, $width, $height) {
  311. $res = imagecreatetruecolor($width, $height);
  312. if ($image->info['extension'] == 'gif') {
  313. // Find out if a transparent color is set, will return -1 if no
  314. // transparent color has been defined in the image.
  315. $transparent = imagecolortransparent($image->resource);
  316. if ($transparent >= 0) {
  317. // Find out the number of colors in the image palette. It will be 0 for
  318. // truecolor images.
  319. $palette_size = imagecolorstotal($image->resource);
  320. if ($palette_size == 0 || $transparent < $palette_size) {
  321. // Set the transparent color in the new resource, either if it is a
  322. // truecolor image or if the transparent color is part of the palette.
  323. // Since the index of the transparency color is a property of the
  324. // image rather than of the palette, it is possible that an image
  325. // could be created with this index set outside the palette size (see
  326. // http://stackoverflow.com/a/3898007).
  327. $transparent_color = imagecolorsforindex($image->resource, $transparent);
  328. $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
  329. // Flood with our new transparent color.
  330. imagefill($res, 0, 0, $transparent);
  331. imagecolortransparent($res, $transparent);
  332. }
  333. else {
  334. imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
  335. }
  336. }
  337. }
  338. elseif ($image->info['extension'] == 'png') {
  339. imagealphablending($res, FALSE);
  340. $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
  341. imagefill($res, 0, 0, $transparency);
  342. imagealphablending($res, TRUE);
  343. imagesavealpha($res, TRUE);
  344. }
  345. else {
  346. imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
  347. }
  348. return $res;
  349. }
  350. /**
  351. * Get details about an image.
  352. *
  353. * @param $image
  354. * An image object.
  355. * @return
  356. * FALSE, if the file could not be found or is not an image. Otherwise, a
  357. * keyed array containing information about the image:
  358. * - "width": Width, in pixels.
  359. * - "height": Height, in pixels.
  360. * - "extension": Commonly used file extension for the image.
  361. * - "mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
  362. *
  363. * @see image_get_info()
  364. */
  365. function image_gd_get_info(stdClass $image) {
  366. $details = FALSE;
  367. $data = @getimagesize($image->source);
  368. if (isset($data) && is_array($data)) {
  369. $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
  370. $extension = isset($extensions[$data[2]]) ? $extensions[$data[2]] : '';
  371. $details = array(
  372. 'width' => $data[0],
  373. 'height' => $data[1],
  374. 'extension' => $extension,
  375. 'mime_type' => $data['mime'],
  376. );
  377. }
  378. return $details;
  379. }
  380. /**
  381. * @} End of "addtogroup image".
  382. */