image.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. <?php
  2. /**
  3. * File contains all the administration image manipulation functions.
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. */
  8. /**
  9. * Crop an Image to a given size.
  10. *
  11. * @since 2.1.0
  12. *
  13. * @param string|int $src The source file or Attachment ID.
  14. * @param int $src_x The start x position to crop from.
  15. * @param int $src_y The start y position to crop from.
  16. * @param int $src_w The width to crop.
  17. * @param int $src_h The height to crop.
  18. * @param int $dst_w The destination width.
  19. * @param int $dst_h The destination height.
  20. * @param int $src_abs Optional. If the source crop points are absolute.
  21. * @param string $dst_file Optional. The destination file to write to.
  22. * @return string|WP_Error New filepath on success, WP_Error on failure.
  23. */
  24. function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
  25. $src_file = $src;
  26. if ( is_numeric( $src ) ) { // Handle int as attachment ID
  27. $src_file = get_attached_file( $src );
  28. if ( ! file_exists( $src_file ) ) {
  29. // If the file doesn't exist, attempt a URL fopen on the src link.
  30. // This can occur with certain file replication plugins.
  31. $src = _load_image_to_edit_path( $src, 'full' );
  32. } else {
  33. $src = $src_file;
  34. }
  35. }
  36. $editor = wp_get_image_editor( $src );
  37. if ( is_wp_error( $editor ) )
  38. return $editor;
  39. $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
  40. if ( is_wp_error( $src ) )
  41. return $src;
  42. if ( ! $dst_file )
  43. $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
  44. /*
  45. * The directory containing the original file may no longer exist when
  46. * using a replication plugin.
  47. */
  48. wp_mkdir_p( dirname( $dst_file ) );
  49. $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
  50. $result = $editor->save( $dst_file );
  51. if ( is_wp_error( $result ) )
  52. return $result;
  53. return $dst_file;
  54. }
  55. /**
  56. * Generate post thumbnail attachment meta data.
  57. *
  58. * @since 2.1.0
  59. *
  60. * @param int $attachment_id Attachment Id to process.
  61. * @param string $file Filepath of the Attached image.
  62. * @return mixed Metadata for attachment.
  63. */
  64. function wp_generate_attachment_metadata( $attachment_id, $file ) {
  65. $attachment = get_post( $attachment_id );
  66. $metadata = array();
  67. $support = false;
  68. $mime_type = get_post_mime_type( $attachment );
  69. if ( preg_match( '!^image/!', $mime_type ) && file_is_displayable_image( $file ) ) {
  70. $imagesize = getimagesize( $file );
  71. $metadata['width'] = $imagesize[0];
  72. $metadata['height'] = $imagesize[1];
  73. // Make the file path relative to the upload dir.
  74. $metadata['file'] = _wp_relative_upload_path($file);
  75. // Make thumbnails and other intermediate sizes.
  76. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  77. $sizes = array();
  78. foreach ( get_intermediate_image_sizes() as $s ) {
  79. $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
  80. if ( isset( $_wp_additional_image_sizes[$s]['width'] ) ) {
  81. // For theme-added sizes
  82. $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] );
  83. } else {
  84. // For default sizes set in options
  85. $sizes[$s]['width'] = get_option( "{$s}_size_w" );
  86. }
  87. if ( isset( $_wp_additional_image_sizes[$s]['height'] ) ) {
  88. // For theme-added sizes
  89. $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] );
  90. } else {
  91. // For default sizes set in options
  92. $sizes[$s]['height'] = get_option( "{$s}_size_h" );
  93. }
  94. if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) ) {
  95. // For theme-added sizes
  96. $sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop'];
  97. } else {
  98. // For default sizes set in options
  99. $sizes[$s]['crop'] = get_option( "{$s}_crop" );
  100. }
  101. }
  102. /**
  103. * Filters the image sizes automatically generated when uploading an image.
  104. *
  105. * @since 2.9.0
  106. * @since 4.4.0 Added the `$metadata` argument.
  107. *
  108. * @param array $sizes An associative array of image sizes.
  109. * @param array $metadata An associative array of image metadata: width, height, file.
  110. */
  111. $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes, $metadata );
  112. if ( $sizes ) {
  113. $editor = wp_get_image_editor( $file );
  114. if ( ! is_wp_error( $editor ) )
  115. $metadata['sizes'] = $editor->multi_resize( $sizes );
  116. } else {
  117. $metadata['sizes'] = array();
  118. }
  119. // Fetch additional metadata from EXIF/IPTC.
  120. $image_meta = wp_read_image_metadata( $file );
  121. if ( $image_meta )
  122. $metadata['image_meta'] = $image_meta;
  123. } elseif ( wp_attachment_is( 'video', $attachment ) ) {
  124. $metadata = wp_read_video_metadata( $file );
  125. $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' );
  126. } elseif ( wp_attachment_is( 'audio', $attachment ) ) {
  127. $metadata = wp_read_audio_metadata( $file );
  128. $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' );
  129. }
  130. if ( $support && ! empty( $metadata['image']['data'] ) ) {
  131. // Check for existing cover.
  132. $hash = md5( $metadata['image']['data'] );
  133. $posts = get_posts( array(
  134. 'fields' => 'ids',
  135. 'post_type' => 'attachment',
  136. 'post_mime_type' => $metadata['image']['mime'],
  137. 'post_status' => 'inherit',
  138. 'posts_per_page' => 1,
  139. 'meta_key' => '_cover_hash',
  140. 'meta_value' => $hash
  141. ) );
  142. $exists = reset( $posts );
  143. if ( ! empty( $exists ) ) {
  144. update_post_meta( $attachment_id, '_thumbnail_id', $exists );
  145. } else {
  146. $ext = '.jpg';
  147. switch ( $metadata['image']['mime'] ) {
  148. case 'image/gif':
  149. $ext = '.gif';
  150. break;
  151. case 'image/png':
  152. $ext = '.png';
  153. break;
  154. }
  155. $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext;
  156. $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
  157. if ( false === $uploaded['error'] ) {
  158. $image_attachment = array(
  159. 'post_mime_type' => $metadata['image']['mime'],
  160. 'post_type' => 'attachment',
  161. 'post_content' => '',
  162. );
  163. /**
  164. * Filters the parameters for the attachment thumbnail creation.
  165. *
  166. * @since 3.9.0
  167. *
  168. * @param array $image_attachment An array of parameters to create the thumbnail.
  169. * @param array $metadata Current attachment metadata.
  170. * @param array $uploaded An array containing the thumbnail path and url.
  171. */
  172. $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded );
  173. $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] );
  174. add_post_meta( $sub_attachment_id, '_cover_hash', $hash );
  175. $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
  176. wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
  177. update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
  178. }
  179. }
  180. }
  181. // Try to create image thumbnails for PDFs
  182. else if ( 'application/pdf' === $mime_type ) {
  183. $fallback_sizes = array(
  184. 'thumbnail',
  185. 'medium',
  186. 'large',
  187. );
  188. /**
  189. * Filters the image sizes generated for non-image mime types.
  190. *
  191. * @since 4.7.0
  192. *
  193. * @param array $fallback_sizes An array of image size names.
  194. * @param array $metadata Current attachment metadata.
  195. */
  196. $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
  197. $sizes = array();
  198. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  199. foreach ( $fallback_sizes as $s ) {
  200. if ( isset( $_wp_additional_image_sizes[ $s ]['width'] ) ) {
  201. $sizes[ $s ]['width'] = intval( $_wp_additional_image_sizes[ $s ]['width'] );
  202. } else {
  203. $sizes[ $s ]['width'] = get_option( "{$s}_size_w" );
  204. }
  205. if ( isset( $_wp_additional_image_sizes[ $s ]['height'] ) ) {
  206. $sizes[ $s ]['height'] = intval( $_wp_additional_image_sizes[ $s ]['height'] );
  207. } else {
  208. $sizes[ $s ]['height'] = get_option( "{$s}_size_h" );
  209. }
  210. if ( isset( $_wp_additional_image_sizes[ $s ]['crop'] ) ) {
  211. $sizes[ $s ]['crop'] = $_wp_additional_image_sizes[ $s ]['crop'];
  212. } else {
  213. // Force thumbnails to be soft crops.
  214. if ( 'thumbnail' !== $s ) {
  215. $sizes[ $s ]['crop'] = get_option( "{$s}_crop" );
  216. }
  217. }
  218. }
  219. // Only load PDFs in an image editor if we're processing sizes.
  220. if ( ! empty( $sizes ) ) {
  221. $editor = wp_get_image_editor( $file );
  222. if ( ! is_wp_error( $editor ) ) { // No support for this type of file
  223. /*
  224. * PDFs may have the same file filename as JPEGs.
  225. * Ensure the PDF preview image does not overwrite any JPEG images that already exist.
  226. */
  227. $dirname = dirname( $file ) . '/';
  228. $ext = '.' . pathinfo( $file, PATHINFO_EXTENSION );
  229. $preview_file = $dirname . wp_unique_filename( $dirname, wp_basename( $file, $ext ) . '-pdf.jpg' );
  230. $uploaded = $editor->save( $preview_file, 'image/jpeg' );
  231. unset( $editor );
  232. // Resize based on the full size image, rather than the source.
  233. if ( ! is_wp_error( $uploaded ) ) {
  234. $editor = wp_get_image_editor( $uploaded['path'] );
  235. unset( $uploaded['path'] );
  236. if ( ! is_wp_error( $editor ) ) {
  237. $metadata['sizes'] = $editor->multi_resize( $sizes );
  238. $metadata['sizes']['full'] = $uploaded;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. // Remove the blob of binary data from the array.
  245. if ( $metadata ) {
  246. unset( $metadata['image']['data'] );
  247. }
  248. /**
  249. * Filters the generated attachment meta data.
  250. *
  251. * @since 2.1.0
  252. *
  253. * @param array $metadata An array of attachment meta data.
  254. * @param int $attachment_id Current attachment ID.
  255. */
  256. return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
  257. }
  258. /**
  259. * Convert a fraction string to a decimal.
  260. *
  261. * @since 2.5.0
  262. *
  263. * @param string $str
  264. * @return int|float
  265. */
  266. function wp_exif_frac2dec($str) {
  267. @list( $n, $d ) = explode( '/', $str );
  268. if ( !empty($d) )
  269. return $n / $d;
  270. return $str;
  271. }
  272. /**
  273. * Convert the exif date format to a unix timestamp.
  274. *
  275. * @since 2.5.0
  276. *
  277. * @param string $str
  278. * @return int
  279. */
  280. function wp_exif_date2ts($str) {
  281. @list( $date, $time ) = explode( ' ', trim($str) );
  282. @list( $y, $m, $d ) = explode( ':', $date );
  283. return strtotime( "{$y}-{$m}-{$d} {$time}" );
  284. }
  285. /**
  286. * Get extended image metadata, exif or iptc as available.
  287. *
  288. * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
  289. * created_timestamp, focal_length, shutter_speed, and title.
  290. *
  291. * The IPTC metadata that is retrieved is APP13, credit, byline, created date
  292. * and time, caption, copyright, and title. Also includes FNumber, Model,
  293. * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
  294. *
  295. * @todo Try other exif libraries if available.
  296. * @since 2.5.0
  297. *
  298. * @param string $file
  299. * @return bool|array False on failure. Image metadata array on success.
  300. */
  301. function wp_read_image_metadata( $file ) {
  302. if ( ! file_exists( $file ) )
  303. return false;
  304. list( , , $sourceImageType ) = @getimagesize( $file );
  305. /*
  306. * EXIF contains a bunch of data we'll probably never need formatted in ways
  307. * that are difficult to use. We'll normalize it and just extract the fields
  308. * that are likely to be useful. Fractions and numbers are converted to
  309. * floats, dates to unix timestamps, and everything else to strings.
  310. */
  311. $meta = array(
  312. 'aperture' => 0,
  313. 'credit' => '',
  314. 'camera' => '',
  315. 'caption' => '',
  316. 'created_timestamp' => 0,
  317. 'copyright' => '',
  318. 'focal_length' => 0,
  319. 'iso' => 0,
  320. 'shutter_speed' => 0,
  321. 'title' => '',
  322. 'orientation' => 0,
  323. 'keywords' => array(),
  324. );
  325. $iptc = array();
  326. /*
  327. * Read IPTC first, since it might contain data not available in exif such
  328. * as caption, description etc.
  329. */
  330. if ( is_callable( 'iptcparse' ) ) {
  331. @getimagesize( $file, $info );
  332. if ( ! empty( $info['APP13'] ) ) {
  333. $iptc = @iptcparse( $info['APP13'] );
  334. // Headline, "A brief synopsis of the caption."
  335. if ( ! empty( $iptc['2#105'][0] ) ) {
  336. $meta['title'] = trim( $iptc['2#105'][0] );
  337. /*
  338. * Title, "Many use the Title field to store the filename of the image,
  339. * though the field may be used in many ways."
  340. */
  341. } elseif ( ! empty( $iptc['2#005'][0] ) ) {
  342. $meta['title'] = trim( $iptc['2#005'][0] );
  343. }
  344. if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
  345. $caption = trim( $iptc['2#120'][0] );
  346. mbstring_binary_safe_encoding();
  347. $caption_length = strlen( $caption );
  348. reset_mbstring_encoding();
  349. if ( empty( $meta['title'] ) && $caption_length < 80 ) {
  350. // Assume the title is stored in 2:120 if it's short.
  351. $meta['title'] = $caption;
  352. }
  353. $meta['caption'] = $caption;
  354. }
  355. if ( ! empty( $iptc['2#110'][0] ) ) // credit
  356. $meta['credit'] = trim( $iptc['2#110'][0] );
  357. elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
  358. $meta['credit'] = trim( $iptc['2#080'][0] );
  359. if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) // created date and time
  360. $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
  361. if ( ! empty( $iptc['2#116'][0] ) ) // copyright
  362. $meta['copyright'] = trim( $iptc['2#116'][0] );
  363. if ( ! empty( $iptc['2#025'][0] ) ) { // keywords array
  364. $meta['keywords'] = array_values( $iptc['2#025'] );
  365. }
  366. }
  367. }
  368. /**
  369. * Filters the image types to check for exif data.
  370. *
  371. * @since 2.5.0
  372. *
  373. * @param array $image_types Image types to check for exif data.
  374. */
  375. if ( is_callable( 'exif_read_data' ) && in_array( $sourceImageType, apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ) ) ) {
  376. $exif = @exif_read_data( $file );
  377. if ( ! empty( $exif['ImageDescription'] ) ) {
  378. mbstring_binary_safe_encoding();
  379. $description_length = strlen( $exif['ImageDescription'] );
  380. reset_mbstring_encoding();
  381. if ( empty( $meta['title'] ) && $description_length < 80 ) {
  382. // Assume the title is stored in ImageDescription
  383. $meta['title'] = trim( $exif['ImageDescription'] );
  384. }
  385. if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) ) {
  386. $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
  387. }
  388. if ( empty( $meta['caption'] ) ) {
  389. $meta['caption'] = trim( $exif['ImageDescription'] );
  390. }
  391. } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) {
  392. $meta['caption'] = trim( $exif['Comments'] );
  393. }
  394. if ( empty( $meta['credit'] ) ) {
  395. if ( ! empty( $exif['Artist'] ) ) {
  396. $meta['credit'] = trim( $exif['Artist'] );
  397. } elseif ( ! empty($exif['Author'] ) ) {
  398. $meta['credit'] = trim( $exif['Author'] );
  399. }
  400. }
  401. if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) {
  402. $meta['copyright'] = trim( $exif['Copyright'] );
  403. }
  404. if ( ! empty( $exif['FNumber'] ) ) {
  405. $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
  406. }
  407. if ( ! empty( $exif['Model'] ) ) {
  408. $meta['camera'] = trim( $exif['Model'] );
  409. }
  410. if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) {
  411. $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] );
  412. }
  413. if ( ! empty( $exif['FocalLength'] ) ) {
  414. $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
  415. }
  416. if ( ! empty( $exif['ISOSpeedRatings'] ) ) {
  417. $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
  418. $meta['iso'] = trim( $meta['iso'] );
  419. }
  420. if ( ! empty( $exif['ExposureTime'] ) ) {
  421. $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
  422. }
  423. if ( ! empty( $exif['Orientation'] ) ) {
  424. $meta['orientation'] = $exif['Orientation'];
  425. }
  426. }
  427. foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
  428. if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) {
  429. $meta[ $key ] = utf8_encode( $meta[ $key ] );
  430. }
  431. }
  432. foreach ( $meta['keywords'] as $key => $keyword ) {
  433. if ( ! seems_utf8( $keyword ) ) {
  434. $meta['keywords'][ $key ] = utf8_encode( $keyword );
  435. }
  436. }
  437. $meta = wp_kses_post_deep( $meta );
  438. /**
  439. * Filters the array of meta data read from an image's exif data.
  440. *
  441. * @since 2.5.0
  442. * @since 4.4.0 The `$iptc` parameter was added.
  443. *
  444. * @param array $meta Image meta data.
  445. * @param string $file Path to image file.
  446. * @param int $sourceImageType Type of image.
  447. * @param array $iptc IPTC data.
  448. */
  449. return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType, $iptc );
  450. }
  451. /**
  452. * Validate that file is an image.
  453. *
  454. * @since 2.5.0
  455. *
  456. * @param string $path File path to test if valid image.
  457. * @return bool True if valid image, false if not valid image.
  458. */
  459. function file_is_valid_image($path) {
  460. $size = @getimagesize($path);
  461. return !empty($size);
  462. }
  463. /**
  464. * Validate that file is suitable for displaying within a web page.
  465. *
  466. * @since 2.5.0
  467. *
  468. * @param string $path File path to test.
  469. * @return bool True if suitable, false if not suitable.
  470. */
  471. function file_is_displayable_image($path) {
  472. $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP );
  473. $info = @getimagesize( $path );
  474. if ( empty( $info ) ) {
  475. $result = false;
  476. } elseif ( ! in_array( $info[2], $displayable_image_types ) ) {
  477. $result = false;
  478. } else {
  479. $result = true;
  480. }
  481. /**
  482. * Filters whether the current image is displayable in the browser.
  483. *
  484. * @since 2.5.0
  485. *
  486. * @param bool $result Whether the image can be displayed. Default true.
  487. * @param string $path Path to the image.
  488. */
  489. return apply_filters( 'file_is_displayable_image', $result, $path );
  490. }
  491. /**
  492. * Load an image resource for editing.
  493. *
  494. * @since 2.9.0
  495. *
  496. * @param string $attachment_id Attachment ID.
  497. * @param string $mime_type Image mime type.
  498. * @param string $size Optional. Image size, defaults to 'full'.
  499. * @return resource|false The resulting image resource on success, false on failure.
  500. */
  501. function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
  502. $filepath = _load_image_to_edit_path( $attachment_id, $size );
  503. if ( empty( $filepath ) )
  504. return false;
  505. switch ( $mime_type ) {
  506. case 'image/jpeg':
  507. $image = imagecreatefromjpeg($filepath);
  508. break;
  509. case 'image/png':
  510. $image = imagecreatefrompng($filepath);
  511. break;
  512. case 'image/gif':
  513. $image = imagecreatefromgif($filepath);
  514. break;
  515. default:
  516. $image = false;
  517. break;
  518. }
  519. if ( is_resource($image) ) {
  520. /**
  521. * Filters the current image being loaded for editing.
  522. *
  523. * @since 2.9.0
  524. *
  525. * @param resource $image Current image.
  526. * @param string $attachment_id Attachment ID.
  527. * @param string $size Image size.
  528. */
  529. $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size );
  530. if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  531. imagealphablending($image, false);
  532. imagesavealpha($image, true);
  533. }
  534. }
  535. return $image;
  536. }
  537. /**
  538. * Retrieve the path or url of an attachment's attached file.
  539. *
  540. * If the attached file is not present on the local filesystem (usually due to replication plugins),
  541. * then the url of the file is returned if url fopen is supported.
  542. *
  543. * @since 3.4.0
  544. * @access private
  545. *
  546. * @param string $attachment_id Attachment ID.
  547. * @param string $size Optional. Image size, defaults to 'full'.
  548. * @return string|false File path or url on success, false on failure.
  549. */
  550. function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
  551. $filepath = get_attached_file( $attachment_id );
  552. if ( $filepath && file_exists( $filepath ) ) {
  553. if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
  554. /**
  555. * Filters the path to the current image.
  556. *
  557. * The filter is evaluated for all image sizes except 'full'.
  558. *
  559. * @since 3.1.0
  560. *
  561. * @param string $path Path to the current image.
  562. * @param string $attachment_id Attachment ID.
  563. * @param string $size Size of the image.
  564. */
  565. $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
  566. }
  567. } elseif ( function_exists( 'fopen' ) && true == ini_get( 'allow_url_fopen' ) ) {
  568. /**
  569. * Filters the image URL if not in the local filesystem.
  570. *
  571. * The filter is only evaluated if fopen is enabled on the server.
  572. *
  573. * @since 3.1.0
  574. *
  575. * @param string $image_url Current image URL.
  576. * @param string $attachment_id Attachment ID.
  577. * @param string $size Size of the image.
  578. */
  579. $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
  580. }
  581. /**
  582. * Filters the returned path or URL of the current image.
  583. *
  584. * @since 2.9.0
  585. *
  586. * @param string|bool $filepath File path or URL to current image, or false.
  587. * @param string $attachment_id Attachment ID.
  588. * @param string $size Size of the image.
  589. */
  590. return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
  591. }
  592. /**
  593. * Copy an existing image file.
  594. *
  595. * @since 3.4.0
  596. * @access private
  597. *
  598. * @param string $attachment_id Attachment ID.
  599. * @return string|false New file path on success, false on failure.
  600. */
  601. function _copy_image_file( $attachment_id ) {
  602. $dst_file = $src_file = get_attached_file( $attachment_id );
  603. if ( ! file_exists( $src_file ) )
  604. $src_file = _load_image_to_edit_path( $attachment_id );
  605. if ( $src_file ) {
  606. $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
  607. $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
  608. /*
  609. * The directory containing the original file may no longer
  610. * exist when using a replication plugin.
  611. */
  612. wp_mkdir_p( dirname( $dst_file ) );
  613. if ( ! @copy( $src_file, $dst_file ) )
  614. $dst_file = false;
  615. } else {
  616. $dst_file = false;
  617. }
  618. return $dst_file;
  619. }