3 * File contains all the administration image manipulation functions.
6 * @subpackage Administration
10 * Crop an Image to a given size.
14 * @param string|int $src The source file or Attachment ID.
15 * @param int $src_x The start x position to crop from.
16 * @param int $src_y The start y position to crop from.
17 * @param int $src_w The width to crop.
18 * @param int $src_h The height to crop.
19 * @param int $dst_w The destination width.
20 * @param int $dst_h The destination height.
21 * @param int $src_abs Optional. If the source crop points are absolute.
22 * @param string $dst_file Optional. The destination file to write to.
23 * @return string|WP_Error New filepath on success, WP_Error on failure.
25 function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
27 if ( is_numeric( $src ) ) { // Handle int as attachment ID
28 $src_file = get_attached_file( $src );
30 if ( ! file_exists( $src_file ) ) {
31 // If the file doesn't exist, attempt a URL fopen on the src link.
32 // This can occur with certain file replication plugins.
33 $src = _load_image_to_edit_path( $src, 'full' );
39 $editor = wp_get_image_editor( $src );
40 if ( is_wp_error( $editor ) )
43 $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
44 if ( is_wp_error( $src ) )
48 $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
51 * The directory containing the original file may no longer exist when
52 * using a replication plugin.
54 wp_mkdir_p( dirname( $dst_file ) );
56 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
58 $result = $editor->save( $dst_file );
59 if ( is_wp_error( $result ) )
66 * Generate post thumbnail attachment meta data.
70 * @param int $attachment_id Attachment Id to process.
71 * @param string $file Filepath of the Attached image.
72 * @return mixed Metadata for attachment.
74 function wp_generate_attachment_metadata( $attachment_id, $file ) {
75 $attachment = get_post( $attachment_id );
79 $mime_type = get_post_mime_type( $attachment );
81 if ( preg_match( '!^image/!', $mime_type ) && file_is_displayable_image( $file ) ) {
82 $imagesize = getimagesize( $file );
83 $metadata['width'] = $imagesize[0];
84 $metadata['height'] = $imagesize[1];
86 // Make the file path relative to the upload dir.
87 $metadata['file'] = _wp_relative_upload_path($file);
89 // Make thumbnails and other intermediate sizes.
90 $_wp_additional_image_sizes = wp_get_additional_image_sizes();
93 foreach ( get_intermediate_image_sizes() as $s ) {
94 $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
95 if ( isset( $_wp_additional_image_sizes[$s]['width'] ) ) {
96 // For theme-added sizes
97 $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] );
99 // For default sizes set in options
100 $sizes[$s]['width'] = get_option( "{$s}_size_w" );
103 if ( isset( $_wp_additional_image_sizes[$s]['height'] ) ) {
104 // For theme-added sizes
105 $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] );
107 // For default sizes set in options
108 $sizes[$s]['height'] = get_option( "{$s}_size_h" );
111 if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) ) {
112 // For theme-added sizes
113 $sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop'];
115 // For default sizes set in options
116 $sizes[$s]['crop'] = get_option( "{$s}_crop" );
121 * Filters the image sizes automatically generated when uploading an image.
124 * @since 4.4.0 Added the `$metadata` argument.
126 * @param array $sizes An associative array of image sizes.
127 * @param array $metadata An associative array of image metadata: width, height, file.
129 $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes, $metadata );
132 $editor = wp_get_image_editor( $file );
134 if ( ! is_wp_error( $editor ) )
135 $metadata['sizes'] = $editor->multi_resize( $sizes );
137 $metadata['sizes'] = array();
140 // Fetch additional metadata from EXIF/IPTC.
141 $image_meta = wp_read_image_metadata( $file );
143 $metadata['image_meta'] = $image_meta;
145 } elseif ( wp_attachment_is( 'video', $attachment ) ) {
146 $metadata = wp_read_video_metadata( $file );
147 $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' );
148 } elseif ( wp_attachment_is( 'audio', $attachment ) ) {
149 $metadata = wp_read_audio_metadata( $file );
150 $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' );
153 if ( $support && ! empty( $metadata['image']['data'] ) ) {
154 // Check for existing cover.
155 $hash = md5( $metadata['image']['data'] );
156 $posts = get_posts( array(
158 'post_type' => 'attachment',
159 'post_mime_type' => $metadata['image']['mime'],
160 'post_status' => 'inherit',
161 'posts_per_page' => 1,
162 'meta_key' => '_cover_hash',
163 'meta_value' => $hash
165 $exists = reset( $posts );
167 if ( ! empty( $exists ) ) {
168 update_post_meta( $attachment_id, '_thumbnail_id', $exists );
171 switch ( $metadata['image']['mime'] ) {
179 $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext;
180 $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
181 if ( false === $uploaded['error'] ) {
182 $image_attachment = array(
183 'post_mime_type' => $metadata['image']['mime'],
184 'post_type' => 'attachment',
185 'post_content' => '',
188 * Filters the parameters for the attachment thumbnail creation.
192 * @param array $image_attachment An array of parameters to create the thumbnail.
193 * @param array $metadata Current attachment metadata.
194 * @param array $uploaded An array containing the thumbnail path and url.
196 $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded );
198 $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] );
199 add_post_meta( $sub_attachment_id, '_cover_hash', $hash );
200 $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
201 wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
202 update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
206 // Try to create image thumbnails for PDFs
207 else if ( 'application/pdf' === $mime_type ) {
208 $fallback_sizes = array(
215 * Filters the image sizes generated for non-image mime types.
219 * @param array $fallback_sizes An array of image size names.
221 $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
224 $_wp_additional_image_sizes = wp_get_additional_image_sizes();
226 foreach ( $fallback_sizes as $s ) {
227 if ( isset( $_wp_additional_image_sizes[ $s ]['width'] ) ) {
228 $sizes[ $s ]['width'] = intval( $_wp_additional_image_sizes[ $s ]['width'] );
230 $sizes[ $s ]['width'] = get_option( "{$s}_size_w" );
233 if ( isset( $_wp_additional_image_sizes[ $s ]['height'] ) ) {
234 $sizes[ $s ]['height'] = intval( $_wp_additional_image_sizes[ $s ]['height'] );
236 $sizes[ $s ]['height'] = get_option( "{$s}_size_h" );
239 if ( isset( $_wp_additional_image_sizes[ $s ]['crop'] ) ) {
240 $sizes[ $s ]['crop'] = $_wp_additional_image_sizes[ $s ]['crop'];
242 // Force thumbnails to be soft crops.
243 if ( ! 'thumbnail' === $s ) {
244 $sizes[ $s ]['crop'] = get_option( "{$s}_crop" );
249 // Only load PDFs in an image editor if we're processing sizes.
250 if ( ! empty( $sizes ) ) {
251 $editor = wp_get_image_editor( $file );
253 if ( ! is_wp_error( $editor ) ) { // No support for this type of file
254 $uploaded = $editor->save( $file, 'image/jpeg' );
257 // Resize based on the full size image, rather than the source.
258 if ( ! is_wp_error( $uploaded ) ) {
259 $editor = wp_get_image_editor( $uploaded['path'] );
260 unset( $uploaded['path'] );
262 if ( ! is_wp_error( $editor ) ) {
263 $metadata['sizes'] = $editor->multi_resize( $sizes );
264 $metadata['sizes']['full'] = $uploaded;
271 // Remove the blob of binary data from the array.
273 unset( $metadata['image']['data'] );
277 * Filters the generated attachment meta data.
281 * @param array $metadata An array of attachment meta data.
282 * @param int $attachment_id Current attachment ID.
284 return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
288 * Convert a fraction string to a decimal.
295 function wp_exif_frac2dec($str) {
296 @list( $n, $d ) = explode( '/', $str );
303 * Convert the exif date format to a unix timestamp.
310 function wp_exif_date2ts($str) {
311 @list( $date, $time ) = explode( ' ', trim($str) );
312 @list( $y, $m, $d ) = explode( ':', $date );
314 return strtotime( "{$y}-{$m}-{$d} {$time}" );
318 * Get extended image metadata, exif or iptc as available.
320 * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
321 * created_timestamp, focal_length, shutter_speed, and title.
323 * The IPTC metadata that is retrieved is APP13, credit, byline, created date
324 * and time, caption, copyright, and title. Also includes FNumber, Model,
325 * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
327 * @todo Try other exif libraries if available.
330 * @param string $file
331 * @return bool|array False on failure. Image metadata array on success.
333 function wp_read_image_metadata( $file ) {
334 if ( ! file_exists( $file ) )
337 list( , , $sourceImageType ) = getimagesize( $file );
340 * EXIF contains a bunch of data we'll probably never need formatted in ways
341 * that are difficult to use. We'll normalize it and just extract the fields
342 * that are likely to be useful. Fractions and numbers are converted to
343 * floats, dates to unix timestamps, and everything else to strings.
350 'created_timestamp' => 0,
354 'shutter_speed' => 0,
357 'keywords' => array(),
362 * Read IPTC first, since it might contain data not available in exif such
363 * as caption, description etc.
365 if ( is_callable( 'iptcparse' ) ) {
366 getimagesize( $file, $info );
368 if ( ! empty( $info['APP13'] ) ) {
369 $iptc = iptcparse( $info['APP13'] );
371 // Headline, "A brief synopsis of the caption."
372 if ( ! empty( $iptc['2#105'][0] ) ) {
373 $meta['title'] = trim( $iptc['2#105'][0] );
375 * Title, "Many use the Title field to store the filename of the image,
376 * though the field may be used in many ways."
378 } elseif ( ! empty( $iptc['2#005'][0] ) ) {
379 $meta['title'] = trim( $iptc['2#005'][0] );
382 if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
383 $caption = trim( $iptc['2#120'][0] );
385 mbstring_binary_safe_encoding();
386 $caption_length = strlen( $caption );
387 reset_mbstring_encoding();
389 if ( empty( $meta['title'] ) && $caption_length < 80 ) {
390 // Assume the title is stored in 2:120 if it's short.
391 $meta['title'] = $caption;
394 $meta['caption'] = $caption;
397 if ( ! empty( $iptc['2#110'][0] ) ) // credit
398 $meta['credit'] = trim( $iptc['2#110'][0] );
399 elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
400 $meta['credit'] = trim( $iptc['2#080'][0] );
402 if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) // created date and time
403 $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
405 if ( ! empty( $iptc['2#116'][0] ) ) // copyright
406 $meta['copyright'] = trim( $iptc['2#116'][0] );
408 if ( ! empty( $iptc['2#025'][0] ) ) { // keywords array
409 $meta['keywords'] = array_values( $iptc['2#025'] );
415 * Filters the image types to check for exif data.
419 * @param array $image_types Image types to check for exif data.
421 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 ) ) ) ) {
422 $exif = @exif_read_data( $file );
424 if ( ! empty( $exif['ImageDescription'] ) ) {
425 mbstring_binary_safe_encoding();
426 $description_length = strlen( $exif['ImageDescription'] );
427 reset_mbstring_encoding();
429 if ( empty( $meta['title'] ) && $description_length < 80 ) {
430 // Assume the title is stored in ImageDescription
431 $meta['title'] = trim( $exif['ImageDescription'] );
434 if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) ) {
435 $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
438 if ( empty( $meta['caption'] ) ) {
439 $meta['caption'] = trim( $exif['ImageDescription'] );
441 } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) {
442 $meta['caption'] = trim( $exif['Comments'] );
445 if ( empty( $meta['credit'] ) ) {
446 if ( ! empty( $exif['Artist'] ) ) {
447 $meta['credit'] = trim( $exif['Artist'] );
448 } elseif ( ! empty($exif['Author'] ) ) {
449 $meta['credit'] = trim( $exif['Author'] );
453 if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) {
454 $meta['copyright'] = trim( $exif['Copyright'] );
456 if ( ! empty( $exif['FNumber'] ) ) {
457 $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
459 if ( ! empty( $exif['Model'] ) ) {
460 $meta['camera'] = trim( $exif['Model'] );
462 if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) {
463 $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] );
465 if ( ! empty( $exif['FocalLength'] ) ) {
466 $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
468 if ( ! empty( $exif['ISOSpeedRatings'] ) ) {
469 $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
470 $meta['iso'] = trim( $meta['iso'] );
472 if ( ! empty( $exif['ExposureTime'] ) ) {
473 $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
475 if ( ! empty( $exif['Orientation'] ) ) {
476 $meta['orientation'] = $exif['Orientation'];
480 foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
481 if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) {
482 $meta[ $key ] = utf8_encode( $meta[ $key ] );
486 foreach ( $meta['keywords'] as $key => $keyword ) {
487 if ( ! seems_utf8( $keyword ) ) {
488 $meta['keywords'][ $key ] = utf8_encode( $keyword );
492 $meta = wp_kses_post_deep( $meta );
495 * Filters the array of meta data read from an image's exif data.
498 * @since 4.4.0 The `$iptc` parameter was added.
500 * @param array $meta Image meta data.
501 * @param string $file Path to image file.
502 * @param int $sourceImageType Type of image.
503 * @param array $iptc IPTC data.
505 return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType, $iptc );
510 * Validate that file is an image.
514 * @param string $path File path to test if valid image.
515 * @return bool True if valid image, false if not valid image.
517 function file_is_valid_image($path) {
518 $size = @getimagesize($path);
519 return !empty($size);
523 * Validate that file is suitable for displaying within a web page.
527 * @param string $path File path to test.
528 * @return bool True if suitable, false if not suitable.
530 function file_is_displayable_image($path) {
531 $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP );
533 $info = @getimagesize( $path );
534 if ( empty( $info ) ) {
536 } elseif ( ! in_array( $info[2], $displayable_image_types ) ) {
543 * Filters whether the current image is displayable in the browser.
547 * @param bool $result Whether the image can be displayed. Default true.
548 * @param string $path Path to the image.
550 return apply_filters( 'file_is_displayable_image', $result, $path );
554 * Load an image resource for editing.
558 * @param string $attachment_id Attachment ID.
559 * @param string $mime_type Image mime type.
560 * @param string $size Optional. Image size, defaults to 'full'.
561 * @return resource|false The resulting image resource on success, false on failure.
563 function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
564 $filepath = _load_image_to_edit_path( $attachment_id, $size );
565 if ( empty( $filepath ) )
568 switch ( $mime_type ) {
570 $image = imagecreatefromjpeg($filepath);
573 $image = imagecreatefrompng($filepath);
576 $image = imagecreatefromgif($filepath);
582 if ( is_resource($image) ) {
584 * Filters the current image being loaded for editing.
588 * @param resource $image Current image.
589 * @param string $attachment_id Attachment ID.
590 * @param string $size Image size.
592 $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size );
593 if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
594 imagealphablending($image, false);
595 imagesavealpha($image, true);
602 * Retrieve the path or url of an attachment's attached file.
604 * If the attached file is not present on the local filesystem (usually due to replication plugins),
605 * then the url of the file is returned if url fopen is supported.
610 * @param string $attachment_id Attachment ID.
611 * @param string $size Optional. Image size, defaults to 'full'.
612 * @return string|false File path or url on success, false on failure.
614 function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
615 $filepath = get_attached_file( $attachment_id );
617 if ( $filepath && file_exists( $filepath ) ) {
618 if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
620 * Filters the path to the current image.
622 * The filter is evaluated for all image sizes except 'full'.
626 * @param string $path Path to the current image.
627 * @param string $attachment_id Attachment ID.
628 * @param string $size Size of the image.
630 $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
632 } elseif ( function_exists( 'fopen' ) && true == ini_get( 'allow_url_fopen' ) ) {
634 * Filters the image URL if not in the local filesystem.
636 * The filter is only evaluated if fopen is enabled on the server.
640 * @param string $image_url Current image URL.
641 * @param string $attachment_id Attachment ID.
642 * @param string $size Size of the image.
644 $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
648 * Filters the returned path or URL of the current image.
652 * @param string|bool $filepath File path or URL to current image, or false.
653 * @param string $attachment_id Attachment ID.
654 * @param string $size Size of the image.
656 return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
660 * Copy an existing image file.
665 * @param string $attachment_id Attachment ID.
666 * @return string|false New file path on success, false on failure.
668 function _copy_image_file( $attachment_id ) {
669 $dst_file = $src_file = get_attached_file( $attachment_id );
670 if ( ! file_exists( $src_file ) )
671 $src_file = _load_image_to_edit_path( $attachment_id );
674 $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
675 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
678 * The directory containing the original file may no longer
679 * exist when using a replication plugin.
681 wp_mkdir_p( dirname( $dst_file ) );
683 if ( ! @copy( $src_file, $dst_file ) )