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

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