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|false New filepath on success, WP_Error or false 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 );
61 * Generate post thumbnail attachment meta data.
65 * @param int $attachment_id Attachment Id to process.
66 * @param string $file Filepath of the Attached image.
67 * @return mixed Metadata for attachment.
69 function wp_generate_attachment_metadata( $attachment_id, $file ) {
70 $attachment = get_post( $attachment_id );
73 if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
74 $imagesize = getimagesize( $file );
75 $metadata['width'] = $imagesize[0];
76 $metadata['height'] = $imagesize[1];
78 // Make the file path relative to the upload dir
79 $metadata['file'] = _wp_relative_upload_path($file);
81 // make thumbnails and other intermediate sizes
82 global $_wp_additional_image_sizes;
84 foreach ( get_intermediate_image_sizes() as $s ) {
85 $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
86 if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
87 $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
89 $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
90 if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
91 $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
93 $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
94 if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
95 $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes
97 $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
100 $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
103 $editor = wp_get_image_editor( $file );
105 if ( ! is_wp_error( $editor ) )
106 $metadata['sizes'] = $editor->multi_resize( $sizes );
108 $metadata['sizes'] = array();
111 // fetch additional metadata from exif/iptc
112 $image_meta = wp_read_image_metadata( $file );
114 $metadata['image_meta'] = $image_meta;
118 return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
122 * Convert a fraction string to a decimal.
129 function wp_exif_frac2dec($str) {
130 @list( $n, $d ) = explode( '/', $str );
137 * Convert the exif date format to a unix timestamp.
144 function wp_exif_date2ts($str) {
145 @list( $date, $time ) = explode( ' ', trim($str) );
146 @list( $y, $m, $d ) = explode( ':', $date );
148 return strtotime( "{$y}-{$m}-{$d} {$time}" );
152 * Get extended image metadata, exif or iptc as available.
154 * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
155 * created_timestamp, focal_length, shutter_speed, and title.
157 * The IPTC metadata that is retrieved is APP13, credit, byline, created date
158 * and time, caption, copyright, and title. Also includes FNumber, Model,
159 * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
161 * @todo Try other exif libraries if available.
164 * @param string $file
165 * @return bool|array False on failure. Image metadata array on success.
167 function wp_read_image_metadata( $file ) {
168 if ( ! file_exists( $file ) )
171 list( , , $sourceImageType ) = getimagesize( $file );
173 // exif contains a bunch of data we'll probably never need formatted in ways
174 // that are difficult to use. We'll normalize it and just extract the fields
175 // that are likely to be useful. Fractions and numbers are converted to
176 // floats, dates to unix timestamps, and everything else to strings.
182 'created_timestamp' => 0,
186 'shutter_speed' => 0,
190 // read iptc first, since it might contain data not available in exif such
191 // as caption, description etc
192 if ( is_callable( 'iptcparse' ) ) {
193 getimagesize( $file, $info );
195 if ( ! empty( $info['APP13'] ) ) {
196 $iptc = iptcparse( $info['APP13'] );
198 // headline, "A brief synopsis of the caption."
199 if ( ! empty( $iptc['2#105'][0] ) )
200 $meta['title'] = trim( $iptc['2#105'][0] );
201 // title, "Many use the Title field to store the filename of the image, though the field may be used in many ways."
202 elseif ( ! empty( $iptc['2#005'][0] ) )
203 $meta['title'] = trim( $iptc['2#005'][0] );
205 if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
206 $caption = trim( $iptc['2#120'][0] );
207 if ( empty( $meta['title'] ) ) {
208 // Assume the title is stored in 2:120 if it's short.
209 if ( strlen( $caption ) < 80 )
210 $meta['title'] = $caption;
212 $meta['caption'] = $caption;
213 } elseif ( $caption != $meta['title'] ) {
214 $meta['caption'] = $caption;
218 if ( ! empty( $iptc['2#110'][0] ) ) // credit
219 $meta['credit'] = trim( $iptc['2#110'][0] );
220 elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
221 $meta['credit'] = trim( $iptc['2#080'][0] );
223 if ( ! empty( $iptc['2#055'][0] ) and ! empty( $iptc['2#060'][0] ) ) // created date and time
224 $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
226 if ( ! empty( $iptc['2#116'][0] ) ) // copyright
227 $meta['copyright'] = trim( $iptc['2#116'][0] );
231 // fetch additional info from exif if available
232 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 ) ) ) ) {
233 $exif = @exif_read_data( $file );
235 if ( !empty( $exif['Title'] ) )
236 $meta['title'] = trim( $exif['Title'] );
238 if ( ! empty( $exif['ImageDescription'] ) ) {
239 if ( empty( $meta['title'] ) && strlen( $exif['ImageDescription'] ) < 80 ) {
240 // Assume the title is stored in ImageDescription
241 $meta['title'] = trim( $exif['ImageDescription'] );
242 if ( ! empty( $exif['COMPUTED']['UserComment'] ) && trim( $exif['COMPUTED']['UserComment'] ) != $meta['title'] )
243 $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] );
244 } elseif ( trim( $exif['ImageDescription'] ) != $meta['title'] ) {
245 $meta['caption'] = trim( $exif['ImageDescription'] );
247 } elseif ( ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) {
248 $meta['caption'] = trim( $exif['Comments'] );
251 if ( ! empty( $exif['Artist'] ) )
252 $meta['credit'] = trim( $exif['Artist'] );
253 elseif ( ! empty($exif['Author'] ) )
254 $meta['credit'] = trim( $exif['Author'] );
256 if ( ! empty( $exif['Copyright'] ) )
257 $meta['copyright'] = trim( $exif['Copyright'] );
258 if ( ! empty($exif['FNumber'] ) )
259 $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
260 if ( ! empty($exif['Model'] ) )
261 $meta['camera'] = trim( $exif['Model'] );
262 if ( ! empty($exif['DateTimeDigitized'] ) )
263 $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized'] );
264 if ( ! empty($exif['FocalLength'] ) )
265 $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] );
266 if ( ! empty($exif['ISOSpeedRatings'] ) ) {
267 $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
268 $meta['iso'] = trim( $meta['iso'] );
270 if ( ! empty($exif['ExposureTime'] ) )
271 $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] );
274 foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) {
275 if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) )
276 $meta[ $key ] = utf8_encode( $meta[ $key ] );
279 return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
284 * Validate that file is an image.
288 * @param string $path File path to test if valid image.
289 * @return bool True if valid image, false if not valid image.
291 function file_is_valid_image($path) {
292 $size = @getimagesize($path);
293 return !empty($size);
297 * Validate that file is suitable for displaying within a web page.
300 * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path.
302 * @param string $path File path to test.
303 * @return bool True if suitable, false if not suitable.
305 function file_is_displayable_image($path) {
306 $info = @getimagesize($path);
309 elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed
314 return apply_filters('file_is_displayable_image', $result, $path);
318 * Load an image resource for editing.
322 * @param string $attachment_id Attachment ID.
323 * @param string $mime_type Image mime type.
324 * @param string $size Optional. Image size, defaults to 'full'.
325 * @return resource|false The resulting image resource on success, false on failure.
327 function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
328 $filepath = _load_image_to_edit_path( $attachment_id, $size );
329 if ( empty( $filepath ) )
332 switch ( $mime_type ) {
334 $image = imagecreatefromjpeg($filepath);
337 $image = imagecreatefrompng($filepath);
340 $image = imagecreatefromgif($filepath);
346 if ( is_resource($image) ) {
347 $image = apply_filters('load_image_to_edit', $image, $attachment_id, $size);
348 if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
349 imagealphablending($image, false);
350 imagesavealpha($image, true);
357 * Retrieve the path or url of an attachment's attached file.
359 * If the attached file is not present on the local filesystem (usually due to replication plugins),
360 * then the url of the file is returned if url fopen is supported.
365 * @param string $attachment_id Attachment ID.
366 * @param string $size Optional. Image size, defaults to 'full'.
367 * @return string|false File path or url on success, false on failure.
369 function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
370 $filepath = get_attached_file( $attachment_id );
372 if ( $filepath && file_exists( $filepath ) ) {
373 if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
374 $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
376 } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) {
377 $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
380 return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
384 * Copy an existing image file.
389 * @param string $attachment_id Attachment ID.
390 * @return string|false New file path on success, false on failure.
392 function _copy_image_file( $attachment_id ) {
393 $dst_file = $src_file = get_attached_file( $attachment_id );
394 if ( ! file_exists( $src_file ) )
395 $src_file = _load_image_to_edit_path( $attachment_id );
398 $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
399 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
401 // The directory containing the original file may no longer exist when
402 // using a replication plugin.
403 wp_mkdir_p( dirname( $dst_file ) );
405 if ( ! @copy( $src_file, $dst_file ) )