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 );
50 // The directory containing the original file may no longer exist when
51 // using a replication plugin.
52 wp_mkdir_p( dirname( $dst_file ) );
54 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
56 $result = $editor->save( $dst_file );
57 if ( is_wp_error( $result ) )
64 * Generate post thumbnail attachment meta data.
68 * @param int $attachment_id Attachment Id to process.
69 * @param string $file Filepath of the Attached image.
70 * @return mixed Metadata for attachment.
72 function wp_generate_attachment_metadata( $attachment_id, $file ) {
73 $attachment = get_post( $attachment_id );
77 if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
78 $imagesize = getimagesize( $file );
79 $metadata['width'] = $imagesize[0];
80 $metadata['height'] = $imagesize[1];
82 // Make the file path relative to the upload dir
83 $metadata['file'] = _wp_relative_upload_path($file);
85 // make thumbnails and other intermediate sizes
86 global $_wp_additional_image_sizes;
89 foreach ( get_intermediate_image_sizes() as $s ) {
90 $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
91 if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
92 $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
94 $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
95 if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
96 $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
98 $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
99 if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
100 $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes
102 $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
105 $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
108 $editor = wp_get_image_editor( $file );
110 if ( ! is_wp_error( $editor ) )
111 $metadata['sizes'] = $editor->multi_resize( $sizes );
113 $metadata['sizes'] = array();
116 // fetch additional metadata from exif/iptc
117 $image_meta = wp_read_image_metadata( $file );
119 $metadata['image_meta'] = $image_meta;
121 } elseif ( preg_match( '#^video/#', get_post_mime_type( $attachment ) ) ) {
122 $metadata = wp_read_video_metadata( $file );
123 $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) && post_type_supports( 'attachment:video', 'thumbnail' );
124 } elseif ( preg_match( '#^audio/#', get_post_mime_type( $attachment ) ) ) {
125 $metadata = wp_read_audio_metadata( $file );
126 $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) && post_type_supports( 'attachment:audio', 'thumbnail' );
129 if ( $support && ! empty( $metadata['image']['data'] ) ) {
131 switch ( $metadata['image']['mime'] ) {
139 $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext;
140 $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] );
141 if ( false === $uploaded['error'] ) {
143 'post_mime_type' => $metadata['image']['mime'],
144 'post_type' => 'attachment',
145 'post_content' => '',
147 $sub_attachment_id = wp_insert_attachment( $attachment, $uploaded['file'] );
148 $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] );
149 wp_update_attachment_metadata( $sub_attachment_id, $attach_data );
150 update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id );
153 // remove the blob of binary data from the array
154 unset( $metadata['image']['data'] );
156 return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
160 * Convert a fraction string to a decimal.
167 function wp_exif_frac2dec($str) {
168 @list( $n, $d ) = explode( '/', $str );
175 * Convert the exif date format to a unix timestamp.
182 function wp_exif_date2ts($str) {
183 @list( $date, $time ) = explode( ' ', trim($str) );
184 @list( $y, $m, $d ) = explode( ':', $date );
186 return strtotime( "{$y}-{$m}-{$d} {$time}" );
190 * Get extended image metadata, exif or iptc as available.
192 * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
193 * created_timestamp, focal_length, shutter_speed, and title.
195 * The IPTC metadata that is retrieved is APP13, credit, byline, created date
196 * and time, caption, copyright, and title. Also includes FNumber, Model,
197 * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
199 * @todo Try other exif libraries if available.
202 * @param string $file
203 * @return bool|array False on failure. Image metadata array on success.
205 function wp_read_image_metadata( $file ) {
206 if ( ! file_exists( $file ) )
209 list( , , $sourceImageType ) = getimagesize( $file );
211 // exif contains a bunch of data we'll probably never need formatted in ways
212 // that are difficult to use. We'll normalize it and just extract the fields
213 // that are likely to be useful. Fractions and numbers are converted to
214 // floats, dates to unix timestamps, and everything else to strings.
220 'created_timestamp' => 0,
224 'shutter_speed' => 0,
228 // read iptc first, since it might contain data not available in exif such
229 // as caption, description etc
230 if ( is_callable( 'iptcparse' ) ) {
231 getimagesize( $file, $info );
233 if ( ! empty( $info['APP13'] ) ) {
234 $iptc = iptcparse( $info['APP13'] );
236 // headline, "A brief synopsis of the caption."
237 if ( ! empty( $iptc['2#105'][0] ) )
238 $meta['title'] = trim( $iptc['2#105'][0] );
239 // title, "Many use the Title field to store the filename of the image, though the field may be used in many ways."
240 elseif ( ! empty( $iptc['2#005'][0] ) )
241 $meta['title'] = trim( $iptc['2#005'][0] );
243 if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
244 $caption = trim( $iptc['2#120'][0] );
245 if ( empty( $meta['title'] ) ) {
246 // Assume the title is stored in 2:120 if it's short.
247 if ( strlen( $caption ) < 80 )
248 $meta['title'] = $caption;
250 $meta['caption'] = $caption;
251 } elseif ( $caption != $meta['title'] ) {
252 $meta['caption'] = $caption;
256 if ( ! empty( $iptc['2#110'][0] ) ) // credit
257 $meta['credit'] = trim( $iptc['2#110'][0] );
258 elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
259 $meta['credit'] = trim( $iptc['2#080'][0] );
261 if ( ! empty( $iptc['2#055'][0] ) and ! empty( $iptc['2#060'][0] ) ) // created date and time
262 $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
264 if ( ! empty( $iptc['2#116'][0] ) ) // copyright
265 $meta['copyright'] = trim( $iptc['2#116'][0] );
269 // fetch additional info from exif if available
270 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 ) ) ) ) {
271 $exif = @exif_read_data( $file );
273 if ( !empty( $exif['Title'] ) )
274 $meta['title'] = trim( $exif['Title'] );
276 if ( ! empty( $exif['ImageDescription'] ) ) {
277 if ( empty( $meta['title'] ) && strlen( $exif['ImageDescription'] ) < 80 ) {
278 // Assume the title is stored in ImageDescription
279 $meta['title'] = trim( $exif['ImageDescription'] );
280 if ( ! empty( $exif['COMPUTED']['UserComment'] ) && trim( $exif['COMPUTED']['UserComment'] ) != $meta['title'] )
281 $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
282 } elseif ( trim( $exif['ImageDescription'] ) != $meta['title'] ) {
283 $meta['caption'] = trim( $exif['ImageDescription'] );
285 } elseif ( ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) {
286 $meta['caption'] = trim( $exif['Comments'] );
289 if ( ! empty( $exif['Artist'] ) )
290 $meta['credit'] = trim( $exif['Artist'] );
291 elseif ( ! empty($exif['Author'] ) )
292 $meta['credit'] = trim( $exif['Author'] );
294 if ( ! empty( $exif['Copyright'] ) )
295 $meta['copyright'] = trim( $exif['Copyright'] );
296 if ( ! empty($exif['FNumber'] ) )
297 $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
298 if ( ! empty($exif['Model'] ) )
299 $meta['camera'] = trim( $exif['Model'] );
300 if ( ! empty($exif['DateTimeDigitized'] ) )
301 $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized'] );
302 if ( ! empty($exif['FocalLength'] ) )
303 $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
304 if ( ! empty($exif['ISOSpeedRatings'] ) ) {
305 $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
306 $meta['iso'] = trim( $meta['iso'] );
308 if ( ! empty($exif['ExposureTime'] ) )
309 $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
312 foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
313 if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) )
314 $meta[ $key ] = utf8_encode( $meta[ $key ] );
317 return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
322 * Validate that file is an image.
326 * @param string $path File path to test if valid image.
327 * @return bool True if valid image, false if not valid image.
329 function file_is_valid_image($path) {
330 $size = @getimagesize($path);
331 return !empty($size);
335 * Validate that file is suitable for displaying within a web page.
338 * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path.
340 * @param string $path File path to test.
341 * @return bool True if suitable, false if not suitable.
343 function file_is_displayable_image($path) {
344 $info = @getimagesize($path);
347 elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed
352 return apply_filters('file_is_displayable_image', $result, $path);
356 * Load an image resource for editing.
360 * @param string $attachment_id Attachment ID.
361 * @param string $mime_type Image mime type.
362 * @param string $size Optional. Image size, defaults to 'full'.
363 * @return resource|false The resulting image resource on success, false on failure.
365 function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
366 $filepath = _load_image_to_edit_path( $attachment_id, $size );
367 if ( empty( $filepath ) )
370 switch ( $mime_type ) {
372 $image = imagecreatefromjpeg($filepath);
375 $image = imagecreatefrompng($filepath);
378 $image = imagecreatefromgif($filepath);
384 if ( is_resource($image) ) {
385 $image = apply_filters('load_image_to_edit', $image, $attachment_id, $size);
386 if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
387 imagealphablending($image, false);
388 imagesavealpha($image, true);
395 * Retrieve the path or url of an attachment's attached file.
397 * If the attached file is not present on the local filesystem (usually due to replication plugins),
398 * then the url of the file is returned if url fopen is supported.
403 * @param string $attachment_id Attachment ID.
404 * @param string $size Optional. Image size, defaults to 'full'.
405 * @return string|false File path or url on success, false on failure.
407 function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
408 $filepath = get_attached_file( $attachment_id );
410 if ( $filepath && file_exists( $filepath ) ) {
411 if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
412 $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
414 } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) {
415 $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
418 return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
422 * Copy an existing image file.
427 * @param string $attachment_id Attachment ID.
428 * @return string|false New file path on success, false on failure.
430 function _copy_image_file( $attachment_id ) {
431 $dst_file = $src_file = get_attached_file( $attachment_id );
432 if ( ! file_exists( $src_file ) )
433 $src_file = _load_image_to_edit_path( $attachment_id );
436 $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
437 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
439 // The directory containing the original file may no longer exist when
440 // using a replication plugin.
441 wp_mkdir_p( dirname( $dst_file ) );
443 if ( ! @copy( $src_file, $dst_file ) )