image.gd.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. $width = $image->info['width'];
  108. $height = $image->info['height'];
  109. // Convert the hexadecimal background value to a color index value.
  110. if (isset($background)) {
  111. $rgb = array();
  112. for ($i = 16; $i >= 0; $i -= 8) {
  113. $rgb[] = (($background >> $i) & 0xFF);
  114. }
  115. $background = imagecolorallocatealpha($image->resource, $rgb[0], $rgb[1], $rgb[2], 0);
  116. }
  117. // Set the background color as transparent if $background is NULL.
  118. else {
  119. // Get the current transparent color.
  120. $background = imagecolortransparent($image->resource);
  121. // If no transparent colors, use white.
  122. if ($background == 0) {
  123. $background = imagecolorallocatealpha($image->resource, 255, 255, 255, 0);
  124. }
  125. }
  126. // Images are assigned a new color palette when rotating, removing any
  127. // transparency flags. For GIF images, keep a record of the transparent color.
  128. if ($image->info['extension'] == 'gif') {
  129. $transparent_index = imagecolortransparent($image->resource);
  130. if ($transparent_index != 0) {
  131. $transparent_gif_color = imagecolorsforindex($image->resource, $transparent_index);
  132. }
  133. }
  134. $image->resource = imagerotate($image->resource, 360 - $degrees, $background);
  135. // GIFs need to reassign the transparent color after performing the rotate.
  136. if (isset($transparent_gif_color)) {
  137. $background = imagecolorexactalpha($image->resource, $transparent_gif_color['red'], $transparent_gif_color['green'], $transparent_gif_color['blue'], $transparent_gif_color['alpha']);
  138. imagecolortransparent($image->resource, $background);
  139. }
  140. $image->info['width'] = imagesx($image->resource);
  141. $image->info['height'] = imagesy($image->resource);
  142. return TRUE;
  143. }
  144. /**
  145. * Crop an image using the GD toolkit.
  146. *
  147. * @param $image
  148. * An image object. The $image->resource, $image->info['width'], and
  149. * $image->info['height'] values will be modified by this call.
  150. * @param $x
  151. * The starting x offset at which to start the crop, in pixels.
  152. * @param $y
  153. * The starting y offset at which to start the crop, in pixels.
  154. * @param $width
  155. * The width of the cropped area, in pixels.
  156. * @param $height
  157. * The height of the cropped area, in pixels.
  158. * @return
  159. * TRUE or FALSE, based on success.
  160. *
  161. * @see image_crop()
  162. */
  163. function image_gd_crop(stdClass $image, $x, $y, $width, $height) {
  164. $res = image_gd_create_tmp($image, $width, $height);
  165. if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) {
  166. return FALSE;
  167. }
  168. // Destroy the original image and return the modified image.
  169. imagedestroy($image->resource);
  170. $image->resource = $res;
  171. $image->info['width'] = $width;
  172. $image->info['height'] = $height;
  173. return TRUE;
  174. }
  175. /**
  176. * Convert an image resource to grayscale.
  177. *
  178. * Note that transparent GIFs loose transparency when desaturated.
  179. *
  180. * @param $image
  181. * An image object. The $image->resource value will be modified by this call.
  182. * @return
  183. * TRUE or FALSE, based on success.
  184. *
  185. * @see image_desaturate()
  186. */
  187. function image_gd_desaturate(stdClass $image) {
  188. // PHP installations using non-bundled GD do not have imagefilter.
  189. if (!function_exists('imagefilter')) {
  190. watchdog('image', 'The image %file could not be desaturated because the imagefilter() function is not available in this PHP installation.', array('%file' => $image->source));
  191. return FALSE;
  192. }
  193. return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);
  194. }
  195. /**
  196. * GD helper function to create an image resource from a file.
  197. *
  198. * @param $image
  199. * An image object. The $image->resource value will populated by this call.
  200. * @return
  201. * TRUE or FALSE, based on success.
  202. *
  203. * @see image_load()
  204. */
  205. function image_gd_load(stdClass $image) {
  206. $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  207. $function = 'imagecreatefrom' . $extension;
  208. if (function_exists($function) && $image->resource = $function($image->source)) {
  209. if (imageistruecolor($image->resource)) {
  210. return TRUE;
  211. }
  212. else {
  213. // Convert indexed images to truecolor, copying the image to a new
  214. // truecolor resource, so that filters work correctly and don't result
  215. // in unnecessary dither.
  216. $resource = image_gd_create_tmp($image, $image->info['width'], $image->info['height']);
  217. if ($resource) {
  218. imagecopy($resource, $image->resource, 0, 0, 0, 0, imagesx($resource), imagesy($resource));
  219. imagedestroy($image->resource);
  220. $image->resource = $resource;
  221. }
  222. }
  223. return (bool) $image->resource;
  224. }
  225. return FALSE;
  226. }
  227. /**
  228. * GD helper to write an image resource to a destination file.
  229. *
  230. * @param $image
  231. * An image object.
  232. * @param $destination
  233. * A string file URI or path where the image should be saved.
  234. * @return
  235. * TRUE or FALSE, based on success.
  236. *
  237. * @see image_save()
  238. */
  239. function image_gd_save(stdClass $image, $destination) {
  240. $scheme = file_uri_scheme($destination);
  241. // Work around lack of stream wrapper support in imagejpeg() and imagepng().
  242. if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
  243. // If destination is not local, save image to temporary local file.
  244. $local_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
  245. if (!isset($local_wrappers[$scheme])) {
  246. $permanent_destination = $destination;
  247. $destination = drupal_tempnam('temporary://', 'gd_');
  248. }
  249. // Convert stream wrapper URI to normal path.
  250. $destination = drupal_realpath($destination);
  251. }
  252. $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
  253. $function = 'image' . $extension;
  254. if (!function_exists($function)) {
  255. return FALSE;
  256. }
  257. if ($extension == 'jpeg') {
  258. $success = $function($image->resource, $destination, variable_get('image_jpeg_quality', 75));
  259. }
  260. else {
  261. // Always save PNG images with full transparency.
  262. if ($extension == 'png') {
  263. imagealphablending($image->resource, FALSE);
  264. imagesavealpha($image->resource, TRUE);
  265. }
  266. $success = $function($image->resource, $destination);
  267. }
  268. // Move temporary local file to remote destination.
  269. if (isset($permanent_destination) && $success) {
  270. return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
  271. }
  272. return $success;
  273. }
  274. /**
  275. * Create a truecolor image preserving transparency from a provided image.
  276. *
  277. * @param $image
  278. * An image object.
  279. * @param $width
  280. * The new width of the new image, in pixels.
  281. * @param $height
  282. * The new height of the new image, in pixels.
  283. * @return
  284. * A GD image handle.
  285. */
  286. function image_gd_create_tmp(stdClass $image, $width, $height) {
  287. $res = imagecreatetruecolor($width, $height);
  288. if ($image->info['extension'] == 'gif') {
  289. // Find out if a transparent color is set, will return -1 if no
  290. // transparent color has been defined in the image.
  291. $transparent = imagecolortransparent($image->resource);
  292. if ($transparent >= 0) {
  293. // Find out the number of colors in the image palette. It will be 0 for
  294. // truecolor images.
  295. $palette_size = imagecolorstotal($image->resource);
  296. if ($palette_size == 0 || $transparent < $palette_size) {
  297. // Set the transparent color in the new resource, either if it is a
  298. // truecolor image or if the transparent color is part of the palette.
  299. // Since the index of the transparency color is a property of the
  300. // image rather than of the palette, it is possible that an image
  301. // could be created with this index set outside the palette size (see
  302. // http://stackoverflow.com/a/3898007).
  303. $transparent_color = imagecolorsforindex($image->resource, $transparent);
  304. $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
  305. // Flood with our new transparent color.
  306. imagefill($res, 0, 0, $transparent);
  307. imagecolortransparent($res, $transparent);
  308. }
  309. else {
  310. imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
  311. }
  312. }
  313. }
  314. elseif ($image->info['extension'] == 'png') {
  315. imagealphablending($res, FALSE);
  316. $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
  317. imagefill($res, 0, 0, $transparency);
  318. imagealphablending($res, TRUE);
  319. imagesavealpha($res, TRUE);
  320. }
  321. else {
  322. imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
  323. }
  324. return $res;
  325. }
  326. /**
  327. * Get details about an image.
  328. *
  329. * @param $image
  330. * An image object.
  331. * @return
  332. * FALSE, if the file could not be found or is not an image. Otherwise, a
  333. * keyed array containing information about the image:
  334. * - "width": Width, in pixels.
  335. * - "height": Height, in pixels.
  336. * - "extension": Commonly used file extension for the image.
  337. * - "mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
  338. *
  339. * @see image_get_info()
  340. */
  341. function image_gd_get_info(stdClass $image) {
  342. $details = FALSE;
  343. $data = @getimagesize($image->source);
  344. if (isset($data) && is_array($data)) {
  345. $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
  346. $extension = isset($extensions[$data[2]]) ? $extensions[$data[2]] : '';
  347. $details = array(
  348. 'width' => $data[0],
  349. 'height' => $data[1],
  350. 'extension' => $extension,
  351. 'mime_type' => $data['mime'],
  352. );
  353. }
  354. return $details;
  355. }
  356. /**
  357. * @} End of "addtogroup image".
  358. */