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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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|GdImage
  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. case 'image/webp':
  66. return ( $image_types & IMG_WEBP ) != 0;
  67. }
  68. return false;
  69. }
  70. /**
  71. * Loads image from $this->file into new GD Resource.
  72. *
  73. * @since 3.5.0
  74. *
  75. * @return true|WP_Error True if loaded successfully; WP_Error on failure.
  76. */
  77. public function load() {
  78. if ( $this->image ) {
  79. return true;
  80. }
  81. if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) {
  82. return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
  83. }
  84. // Set artificially high because GD uses uncompressed images in memory.
  85. wp_raise_memory_limit( 'image' );
  86. $file_contents = @file_get_contents( $this->file );
  87. if ( ! $file_contents ) {
  88. return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
  89. }
  90. // WebP may not work with imagecreatefromstring().
  91. if (
  92. function_exists( 'imagecreatefromwebp' ) &&
  93. ( 'image/webp' === wp_get_image_mime( $this->file ) )
  94. ) {
  95. $this->image = @imagecreatefromwebp( $this->file );
  96. } else {
  97. $this->image = @imagecreatefromstring( $file_contents );
  98. }
  99. if ( ! is_gd_image( $this->image ) ) {
  100. return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
  101. }
  102. $size = wp_getimagesize( $this->file );
  103. if ( ! $size ) {
  104. return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
  105. }
  106. if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
  107. imagealphablending( $this->image, false );
  108. imagesavealpha( $this->image, true );
  109. }
  110. $this->update_size( $size[0], $size[1] );
  111. $this->mime_type = $size['mime'];
  112. return $this->set_quality();
  113. }
  114. /**
  115. * Sets or updates current image size.
  116. *
  117. * @since 3.5.0
  118. *
  119. * @param int $width
  120. * @param int $height
  121. * @return true
  122. */
  123. protected function update_size( $width = false, $height = false ) {
  124. if ( ! $width ) {
  125. $width = imagesx( $this->image );
  126. }
  127. if ( ! $height ) {
  128. $height = imagesy( $this->image );
  129. }
  130. return parent::update_size( $width, $height );
  131. }
  132. /**
  133. * Resizes current image.
  134. *
  135. * Wraps `::_resize()` which returns a GD resource or GdImage instance.
  136. *
  137. * At minimum, either a height or width must be provided. If one of the two is set
  138. * to null, the resize will maintain aspect ratio according to the provided dimension.
  139. *
  140. * @since 3.5.0
  141. *
  142. * @param int|null $max_w Image width.
  143. * @param int|null $max_h Image height.
  144. * @param bool $crop
  145. * @return true|WP_Error
  146. */
  147. public function resize( $max_w, $max_h, $crop = false ) {
  148. if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) {
  149. return true;
  150. }
  151. $resized = $this->_resize( $max_w, $max_h, $crop );
  152. if ( is_gd_image( $resized ) ) {
  153. imagedestroy( $this->image );
  154. $this->image = $resized;
  155. return true;
  156. } elseif ( is_wp_error( $resized ) ) {
  157. return $resized;
  158. }
  159. return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
  160. }
  161. /**
  162. * @param int $max_w
  163. * @param int $max_h
  164. * @param bool|array $crop
  165. * @return resource|GdImage|WP_Error
  166. */
  167. protected function _resize( $max_w, $max_h, $crop = false ) {
  168. $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
  169. if ( ! $dims ) {
  170. return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file );
  171. }
  172. list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
  173. $resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
  174. imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  175. if ( is_gd_image( $resized ) ) {
  176. $this->update_size( $dst_w, $dst_h );
  177. return $resized;
  178. }
  179. return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
  180. }
  181. /**
  182. * Create multiple smaller images from a single source.
  183. *
  184. * Attempts to create all sub-sizes and returns the meta data at the end. This
  185. * may result in the server running out of resources. When it fails there may be few
  186. * "orphaned" images left over as the meta data is never returned and saved.
  187. *
  188. * As of 5.3.0 the preferred way to do this is with `make_subsize()`. It creates
  189. * the new images one at a time and allows for the meta data to be saved after
  190. * each new image is created.
  191. *
  192. * @since 3.5.0
  193. *
  194. * @param array $sizes {
  195. * An array of image size data arrays.
  196. *
  197. * Either a height or width must be provided.
  198. * If one of the two is set to null, the resize will
  199. * maintain aspect ratio according to the source image.
  200. *
  201. * @type array ...$0 {
  202. * Array of height, width values, and whether to crop.
  203. *
  204. * @type int $width Image width. Optional if `$height` is specified.
  205. * @type int $height Image height. Optional if `$width` is specified.
  206. * @type bool $crop Optional. Whether to crop the image. Default false.
  207. * }
  208. * }
  209. * @return array An array of resized images' metadata by size.
  210. */
  211. public function multi_resize( $sizes ) {
  212. $metadata = array();
  213. foreach ( $sizes as $size => $size_data ) {
  214. $meta = $this->make_subsize( $size_data );
  215. if ( ! is_wp_error( $meta ) ) {
  216. $metadata[ $size ] = $meta;
  217. }
  218. }
  219. return $metadata;
  220. }
  221. /**
  222. * Create an image sub-size and return the image meta data value for it.
  223. *
  224. * @since 5.3.0
  225. *
  226. * @param array $size_data {
  227. * Array of size data.
  228. *
  229. * @type int $width The maximum width in pixels.
  230. * @type int $height The maximum height in pixels.
  231. * @type bool $crop Whether to crop the image to exact dimensions.
  232. * }
  233. * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta,
  234. * WP_Error object on error.
  235. */
  236. public function make_subsize( $size_data ) {
  237. if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
  238. return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) );
  239. }
  240. $orig_size = $this->size;
  241. if ( ! isset( $size_data['width'] ) ) {
  242. $size_data['width'] = null;
  243. }
  244. if ( ! isset( $size_data['height'] ) ) {
  245. $size_data['height'] = null;
  246. }
  247. if ( ! isset( $size_data['crop'] ) ) {
  248. $size_data['crop'] = false;
  249. }
  250. $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
  251. if ( is_wp_error( $resized ) ) {
  252. $saved = $resized;
  253. } else {
  254. $saved = $this->_save( $resized );
  255. imagedestroy( $resized );
  256. }
  257. $this->size = $orig_size;
  258. if ( ! is_wp_error( $saved ) ) {
  259. unset( $saved['path'] );
  260. }
  261. return $saved;
  262. }
  263. /**
  264. * Crops Image.
  265. *
  266. * @since 3.5.0
  267. *
  268. * @param int $src_x The start x position to crop from.
  269. * @param int $src_y The start y position to crop from.
  270. * @param int $src_w The width to crop.
  271. * @param int $src_h The height to crop.
  272. * @param int $dst_w Optional. The destination width.
  273. * @param int $dst_h Optional. The destination height.
  274. * @param bool $src_abs Optional. If the source crop points are absolute.
  275. * @return true|WP_Error
  276. */
  277. public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
  278. // If destination width/height isn't specified,
  279. // use same as width/height from source.
  280. if ( ! $dst_w ) {
  281. $dst_w = $src_w;
  282. }
  283. if ( ! $dst_h ) {
  284. $dst_h = $src_h;
  285. }
  286. foreach ( array( $src_w, $src_h, $dst_w, $dst_h ) as $value ) {
  287. if ( ! is_numeric( $value ) || (int) $value <= 0 ) {
  288. return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
  289. }
  290. }
  291. $dst = wp_imagecreatetruecolor( (int) $dst_w, (int) $dst_h );
  292. if ( $src_abs ) {
  293. $src_w -= $src_x;
  294. $src_h -= $src_y;
  295. }
  296. if ( function_exists( 'imageantialias' ) ) {
  297. imageantialias( $dst, true );
  298. }
  299. imagecopyresampled( $dst, $this->image, 0, 0, (int) $src_x, (int) $src_y, (int) $dst_w, (int) $dst_h, (int) $src_w, (int) $src_h );
  300. if ( is_gd_image( $dst ) ) {
  301. imagedestroy( $this->image );
  302. $this->image = $dst;
  303. $this->update_size();
  304. return true;
  305. }
  306. return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
  307. }
  308. /**
  309. * Rotates current image counter-clockwise by $angle.
  310. * Ported from image-edit.php
  311. *
  312. * @since 3.5.0
  313. *
  314. * @param float $angle
  315. * @return true|WP_Error
  316. */
  317. public function rotate( $angle ) {
  318. if ( function_exists( 'imagerotate' ) ) {
  319. $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
  320. $rotated = imagerotate( $this->image, $angle, $transparency );
  321. if ( is_gd_image( $rotated ) ) {
  322. imagealphablending( $rotated, true );
  323. imagesavealpha( $rotated, true );
  324. imagedestroy( $this->image );
  325. $this->image = $rotated;
  326. $this->update_size();
  327. return true;
  328. }
  329. }
  330. return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file );
  331. }
  332. /**
  333. * Flips current image.
  334. *
  335. * @since 3.5.0
  336. *
  337. * @param bool $horz Flip along Horizontal Axis.
  338. * @param bool $vert Flip along Vertical Axis.
  339. * @return true|WP_Error
  340. */
  341. public function flip( $horz, $vert ) {
  342. $w = $this->size['width'];
  343. $h = $this->size['height'];
  344. $dst = wp_imagecreatetruecolor( $w, $h );
  345. if ( is_gd_image( $dst ) ) {
  346. $sx = $vert ? ( $w - 1 ) : 0;
  347. $sy = $horz ? ( $h - 1 ) : 0;
  348. $sw = $vert ? -$w : $w;
  349. $sh = $horz ? -$h : $h;
  350. if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
  351. imagedestroy( $this->image );
  352. $this->image = $dst;
  353. return true;
  354. }
  355. }
  356. return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
  357. }
  358. /**
  359. * Saves current in-memory image to file.
  360. *
  361. * @since 3.5.0
  362. * @since 5.9.0 Renamed `$filename` to `$destfilename` to match parent class
  363. * for PHP 8 named parameter support.
  364. * @since 6.0.0 The `$filesize` value was added to the returned array.
  365. *
  366. * @param string|null $destfilename Optional. Destination filename. Default null.
  367. * @param string|null $mime_type Optional. The mime-type. Default null.
  368. * @return array|WP_Error {
  369. * Array on success or WP_Error if the file failed to save.
  370. *
  371. * @type string $path Path to the image file.
  372. * @type string $file Name of the image file.
  373. * @type int $width Image width.
  374. * @type int $height Image height.
  375. * @type string $mime-type The mime type of the image.
  376. * @type int $filesize File size of the image.
  377. * }
  378. */
  379. public function save( $destfilename = null, $mime_type = null ) {
  380. $saved = $this->_save( $this->image, $destfilename, $mime_type );
  381. if ( ! is_wp_error( $saved ) ) {
  382. $this->file = $saved['path'];
  383. $this->mime_type = $saved['mime-type'];
  384. }
  385. return $saved;
  386. }
  387. /**
  388. * @since 3.5.0
  389. * @since 6.0.0 The `$filesize` value was added to the returned array.
  390. *
  391. * @param resource|GdImage $image
  392. * @param string|null $filename
  393. * @param string|null $mime_type
  394. * @return array|WP_Error {
  395. * Array on success or WP_Error if the file failed to save.
  396. *
  397. * @type string $path Path to the image file.
  398. * @type string $file Name of the image file.
  399. * @type int $width Image width.
  400. * @type int $height Image height.
  401. * @type string $mime-type The mime type of the image.
  402. * @type int $filesize File size of the image.
  403. * }
  404. */
  405. protected function _save( $image, $filename = null, $mime_type = null ) {
  406. list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
  407. if ( ! $filename ) {
  408. $filename = $this->generate_filename( null, null, $extension );
  409. }
  410. if ( 'image/gif' === $mime_type ) {
  411. if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) {
  412. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  413. }
  414. } elseif ( 'image/png' === $mime_type ) {
  415. // Convert from full colors to index colors, like original PNG.
  416. if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) {
  417. imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
  418. }
  419. if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) {
  420. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  421. }
  422. } elseif ( 'image/jpeg' === $mime_type ) {
  423. if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
  424. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  425. }
  426. } elseif ( 'image/webp' == $mime_type ) {
  427. if ( ! function_exists( 'imagewebp' ) || ! $this->make_image( $filename, 'imagewebp', array( $image, $filename, $this->get_quality() ) ) ) {
  428. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  429. }
  430. } else {
  431. return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
  432. }
  433. // Set correct file permissions.
  434. $stat = stat( dirname( $filename ) );
  435. $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits.
  436. chmod( $filename, $perms );
  437. return array(
  438. 'path' => $filename,
  439. /**
  440. * Filters the name of the saved image file.
  441. *
  442. * @since 2.6.0
  443. *
  444. * @param string $filename Name of the file.
  445. */
  446. 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
  447. 'width' => $this->size['width'],
  448. 'height' => $this->size['height'],
  449. 'mime-type' => $mime_type,
  450. 'filesize' => wp_filesize( $filename ),
  451. );
  452. }
  453. /**
  454. * Returns stream of current image.
  455. *
  456. * @since 3.5.0
  457. *
  458. * @param string $mime_type The mime type of the image.
  459. * @return bool True on success, false on failure.
  460. */
  461. public function stream( $mime_type = null ) {
  462. list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
  463. switch ( $mime_type ) {
  464. case 'image/png':
  465. header( 'Content-Type: image/png' );
  466. return imagepng( $this->image );
  467. case 'image/gif':
  468. header( 'Content-Type: image/gif' );
  469. return imagegif( $this->image );
  470. case 'image/webp':
  471. if ( function_exists( 'imagewebp' ) ) {
  472. header( 'Content-Type: image/webp' );
  473. return imagewebp( $this->image, null, $this->get_quality() );
  474. }
  475. // Fall back to the default if webp isn't supported.
  476. default:
  477. header( 'Content-Type: image/jpeg' );
  478. return imagejpeg( $this->image, null, $this->get_quality() );
  479. }
  480. }
  481. /**
  482. * Either calls editor's save function or handles file as a stream.
  483. *
  484. * @since 3.5.0
  485. *
  486. * @param string $filename
  487. * @param callable $callback
  488. * @param array $arguments
  489. * @return bool
  490. */
  491. protected function make_image( $filename, $callback, $arguments ) {
  492. if ( wp_is_stream( $filename ) ) {
  493. $arguments[1] = null;
  494. }
  495. return parent::make_image( $filename, $callback, $arguments );
  496. }
  497. }