class-wp-image-editor-gd.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. /**
  3. * WordPress GD Image Editor
  4. *
  5. * @package WordPress
  6. * @subpackage Image_Editor
  7. */
  8. /**
  9. * WordPress Image Editor Class for Image Manipulation through GD
  10. *
  11. * @since 3.5.0
  12. *
  13. * @see WP_Image_Editor
  14. */
  15. class WP_Image_Editor_GD extends WP_Image_Editor {
  16. /**
  17. * GD Resource.
  18. *
  19. * @var resource
  20. */
  21. protected $image;
  22. public function __destruct() {
  23. if ( $this->image ) {
  24. // we don't need the original in memory anymore
  25. imagedestroy( $this->image );
  26. }
  27. }
  28. /**
  29. * Checks to see if current environment supports GD.
  30. *
  31. * @since 3.5.0
  32. *
  33. * @param array $args
  34. * @return bool
  35. */
  36. public static function test( $args = array() ) {
  37. if ( ! extension_loaded( 'gd' ) || ! function_exists( 'gd_info' ) ) {
  38. return false;
  39. }
  40. // On some setups GD library does not provide imagerotate() - Ticket #11536
  41. if ( isset( $args['methods'] ) &&
  42. in_array( 'rotate', $args['methods'], true ) &&
  43. ! function_exists( 'imagerotate' ) ) {
  44. return false;
  45. }
  46. return true;
  47. }
  48. /**
  49. * Checks to see if editor supports the mime-type specified.
  50. *
  51. * @since 3.5.0
  52. *
  53. * @param string $mime_type
  54. * @return bool
  55. */
  56. public static function supports_mime_type( $mime_type ) {
  57. $image_types = imagetypes();
  58. switch ( $mime_type ) {
  59. case 'image/jpeg':
  60. return ( $image_types & IMG_JPG ) != 0;
  61. case 'image/png':
  62. return ( $image_types & IMG_PNG ) != 0;
  63. case 'image/gif':
  64. return ( $image_types & IMG_GIF ) != 0;
  65. }
  66. return false;
  67. }
  68. /**
  69. * Loads image from $this->file into new GD Resource.
  70. *
  71. * @since 3.5.0
  72. *
  73. * @return bool|WP_Error True if loaded successfully; WP_Error on failure.
  74. */
  75. public function load() {
  76. if ( $this->image ) {
  77. return true;
  78. }
  79. if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) {
  80. return new WP_Error( 'error_loading_image', __( 'File doesn&#8217;t exist?' ), $this->file );
  81. }
  82. // Set artificially high because GD uses uncompressed images in memory.
  83. wp_raise_memory_limit( 'image' );
  84. $this->image = @imagecreatefromstring( file_get_contents( $this->file ) );
  85. if ( ! is_resource( $this->image ) ) {
  86. return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
  87. }
  88. $size = @getimagesize( $this->file );
  89. if ( ! $size ) {
  90. return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
  91. }
  92. if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
  93. imagealphablending( $this->image, false );
  94. imagesavealpha( $this->image, true );
  95. }
  96. $this->update_size( $size[0], $size[1] );
  97. $this->mime_type = $size['mime'];
  98. return $this->set_quality();
  99. }
  100. /**
  101. * Sets or updates current image size.
  102. *
  103. * @since 3.5.0
  104. *
  105. * @param int $width
  106. * @param int $height
  107. * @return true
  108. */
  109. protected function update_size( $width = false, $height = false ) {
  110. if ( ! $width ) {
  111. $width = imagesx( $this->image );
  112. }
  113. if ( ! $height ) {
  114. $height = imagesy( $this->image );
  115. }
  116. return parent::update_size( $width, $height );
  117. }
  118. /**
  119. * Resizes current image.
  120. * Wraps _resize, since _resize returns a GD Resource.
  121. *
  122. * At minimum, either a height or width must be provided.
  123. * If one of the two is set to null, the resize will
  124. * maintain aspect ratio according to the provided dimension.
  125. *
  126. * @since 3.5.0
  127. *
  128. * @param int|null $max_w Image width.
  129. * @param int|null $max_h Image height.
  130. * @param bool $crop
  131. * @return true|WP_Error
  132. */
  133. public function resize( $max_w, $max_h, $crop = false ) {
  134. if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) {
  135. return true;
  136. }
  137. $resized = $this->_resize( $max_w, $max_h, $crop );
  138. if ( is_resource( $resized ) ) {
  139. imagedestroy( $this->image );
  140. $this->image = $resized;
  141. return true;
  142. } elseif ( is_wp_error( $resized ) ) {
  143. return $resized;
  144. }
  145. return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
  146. }
  147. /**
  148. * @param int $max_w
  149. * @param int $max_h
  150. * @param bool|array $crop
  151. * @return resource|WP_Error
  152. */
  153. protected function _resize( $max_w, $max_h, $crop = false ) {
  154. $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
  155. if ( ! $dims ) {
  156. return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file );
  157. }
  158. list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
  159. $resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
  160. imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  161. if ( is_resource( $resized ) ) {
  162. $this->update_size( $dst_w, $dst_h );
  163. return $resized;
  164. }
  165. return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
  166. }
  167. /**
  168. * Create multiple smaller images from a single source.
  169. *
  170. * Attempts to create all sub-sizes and returns the meta data at the end. This
  171. * may result in the server running out of resources. When it fails there may be few
  172. * "orphaned" images left over as the meta data is never returned and saved.
  173. *
  174. * As of 5.3.0 the preferred way to do this is with `make_subsize()`. It creates
  175. * the new images one at a time and allows for the meta data to be saved after
  176. * each new image is created.
  177. *
  178. * @since 3.5.0
  179. *
  180. * @param array $sizes {
  181. * An array of image size data arrays.
  182. *
  183. * Either a height or width must be provided.
  184. * If one of the two is set to null, the resize will
  185. * maintain aspect ratio according to the source image.
  186. *
  187. * @type array $size {
  188. * Array of height, width values, and whether to crop.
  189. *
  190. * @type int $width Image width. Optional if `$height` is specified.
  191. * @type int $height Image height. Optional if `$width` is specified.
  192. * @type bool $crop Optional. Whether to crop the image. Default false.
  193. * }
  194. * }
  195. * @return array An array of resized images' metadata by size.
  196. */
  197. public function multi_resize( $sizes ) {
  198. $metadata = array();
  199. foreach ( $sizes as $size => $size_data ) {
  200. $meta = $this->make_subsize( $size_data );
  201. if ( ! is_wp_error( $meta ) ) {
  202. $metadata[ $size ] = $meta;
  203. }
  204. }
  205. return $metadata;
  206. }
  207. /**
  208. * Create an image sub-size and return the image meta data value for it.
  209. *
  210. * @since 5.3.0
  211. *
  212. * @param array $size_data Array of width, height, and whether to crop.
  213. * @return WP_Error|array WP_Error on error, or the image data array for inclusion in the `sizes` array in the image meta.
  214. */
  215. public function make_subsize( $size_data ) {
  216. if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
  217. return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) );
  218. }
  219. $orig_size = $this->size;
  220. if ( ! isset( $size_data['width'] ) ) {
  221. $size_data['width'] = null;
  222. }
  223. if ( ! isset( $size_data['height'] ) ) {
  224. $size_data['height'] = null;
  225. }
  226. if ( ! isset( $size_data['crop'] ) ) {
  227. $size_data['crop'] = false;
  228. }
  229. $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
  230. if ( is_wp_error( $resized ) ) {
  231. $saved = $resized;
  232. } else {
  233. $saved = $this->_save( $resized );
  234. imagedestroy( $resized );
  235. }
  236. $this->size = $orig_size;
  237. if ( ! is_wp_error( $saved ) ) {
  238. unset( $saved['path'] );
  239. }
  240. return $saved;
  241. }
  242. /**
  243. * Crops Image.
  244. *
  245. * @since 3.5.0
  246. *
  247. * @param int $src_x The start x position to crop from.
  248. * @param int $src_y The start y position to crop from.
  249. * @param int $src_w The width to crop.
  250. * @param int $src_h The height to crop.
  251. * @param int $dst_w Optional. The destination width.
  252. * @param int $dst_h Optional. The destination height.
  253. * @param bool $src_abs Optional. If the source crop points are absolute.
  254. * @return bool|WP_Error
  255. */
  256. public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
  257. // If destination width/height isn't specified, use same as
  258. // width/height from source.
  259. if ( ! $dst_w ) {
  260. $dst_w = $src_w;
  261. }
  262. if ( ! $dst_h ) {
  263. $dst_h = $src_h;
  264. }
  265. $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
  266. if ( $src_abs ) {
  267. $src_w -= $src_x;
  268. $src_h -= $src_y;
  269. }
  270. if ( function_exists( 'imageantialias' ) ) {
  271. imageantialias( $dst, true );
  272. }
  273. imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  274. if ( is_resource( $dst ) ) {
  275. imagedestroy( $this->image );
  276. $this->image = $dst;
  277. $this->update_size();
  278. return true;
  279. }
  280. return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
  281. }
  282. /**
  283. * Rotates current image counter-clockwise by $angle.
  284. * Ported from image-edit.php
  285. *
  286. * @since 3.5.0
  287. *
  288. * @param float $angle
  289. * @return true|WP_Error
  290. */
  291. public function rotate( $angle ) {
  292. if ( function_exists( 'imagerotate' ) ) {
  293. $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
  294. $rotated = imagerotate( $this->image, $angle, $transparency );
  295. if ( is_resource( $rotated ) ) {
  296. imagealphablending( $rotated, true );
  297. imagesavealpha( $rotated, true );
  298. imagedestroy( $this->image );
  299. $this->image = $rotated;
  300. $this->update_size();
  301. return true;
  302. }
  303. }
  304. return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file );
  305. }
  306. /**
  307. * Flips current image.
  308. *
  309. * @since 3.5.0
  310. *
  311. * @param bool $horz Flip along Horizontal Axis.
  312. * @param bool $vert Flip along Vertical Axis.
  313. * @return true|WP_Error
  314. */
  315. public function flip( $horz, $vert ) {
  316. $w = $this->size['width'];
  317. $h = $this->size['height'];
  318. $dst = wp_imagecreatetruecolor( $w, $h );
  319. if ( is_resource( $dst ) ) {
  320. $sx = $vert ? ( $w - 1 ) : 0;
  321. $sy = $horz ? ( $h - 1 ) : 0;
  322. $sw = $vert ? -$w : $w;
  323. $sh = $horz ? -$h : $h;
  324. if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
  325. imagedestroy( $this->image );
  326. $this->image = $dst;
  327. return true;
  328. }
  329. }
  330. return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
  331. }
  332. /**
  333. * Saves current in-memory image to file.
  334. *
  335. * @since 3.5.0
  336. *
  337. * @param string|null $filename
  338. * @param string|null $mime_type
  339. * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
  340. */
  341. public function save( $filename = null, $mime_type = null ) {
  342. $saved = $this->_save( $this->image, $filename, $mime_type );
  343. if ( ! is_wp_error( $saved ) ) {
  344. $this->file = $saved['path'];
  345. $this->mime_type = $saved['mime-type'];
  346. }
  347. return $saved;
  348. }
  349. /**
  350. * @param resource $image
  351. * @param string|null $filename
  352. * @param string|null $mime_type
  353. * @return WP_Error|array
  354. */
  355. protected function _save( $image, $filename = null, $mime_type = null ) {
  356. list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
  357. if ( ! $filename ) {
  358. $filename = $this->generate_filename( null, null, $extension );
  359. }
  360. if ( 'image/gif' === $mime_type ) {
  361. if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) {
  362. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  363. }
  364. } elseif ( 'image/png' === $mime_type ) {
  365. // convert from full colors to index colors, like original PNG.
  366. if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) {
  367. imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
  368. }
  369. if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) {
  370. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  371. }
  372. } elseif ( 'image/jpeg' === $mime_type ) {
  373. if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
  374. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  375. }
  376. } else {
  377. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  378. }
  379. // Set correct file permissions
  380. $stat = stat( dirname( $filename ) );
  381. $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
  382. chmod( $filename, $perms );
  383. /**
  384. * Filters the name of the saved image file.
  385. *
  386. * @since 2.6.0
  387. *
  388. * @param string $filename Name of the file.
  389. */
  390. return array(
  391. 'path' => $filename,
  392. 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
  393. 'width' => $this->size['width'],
  394. 'height' => $this->size['height'],
  395. 'mime-type' => $mime_type,
  396. );
  397. }
  398. /**
  399. * Returns stream of current image.
  400. *
  401. * @since 3.5.0
  402. *
  403. * @param string $mime_type The mime type of the image.
  404. * @return bool True on success, false on failure.
  405. */
  406. public function stream( $mime_type = null ) {
  407. list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
  408. switch ( $mime_type ) {
  409. case 'image/png':
  410. header( 'Content-Type: image/png' );
  411. return imagepng( $this->image );
  412. case 'image/gif':
  413. header( 'Content-Type: image/gif' );
  414. return imagegif( $this->image );
  415. default:
  416. header( 'Content-Type: image/jpeg' );
  417. return imagejpeg( $this->image, null, $this->get_quality() );
  418. }
  419. }
  420. /**
  421. * Either calls editor's save function or handles file as a stream.
  422. *
  423. * @since 3.5.0
  424. *
  425. * @param string|stream $filename
  426. * @param callable $function
  427. * @param array $arguments
  428. * @return bool
  429. */
  430. protected function make_image( $filename, $function, $arguments ) {
  431. if ( wp_is_stream( $filename ) ) {
  432. $arguments[1] = null;
  433. }
  434. return parent::make_image( $filename, $function, $arguments );
  435. }
  436. }