3 * File contains all the administration image manipulation functions.
6 * @subpackage Administration
10 * Create a thumbnail from an Image given a maximum side size.
12 * This function can handle most image file formats which PHP supports. If PHP
13 * does not have the functionality to save in a file of the same format, the
14 * thumbnail will be created as a jpeg.
18 * @param mixed $file Filename of the original image, Or attachment id.
19 * @param int $max_side Maximum length of a single side for the thumbnail.
20 * @param mixed $deprecated Never used.
21 * @return string Thumbnail path on success, Error string on failure.
23 function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) {
24 if ( !empty( $deprecated ) )
25 _deprecated_argument( __FUNCTION__, '1.2' );
26 $thumbpath = image_resize( $file, $max_side, $max_side );
27 return apply_filters( 'wp_create_thumbnail', $thumbpath );
31 * Crop an Image to a given size.
35 * @param string|int $src The source file or Attachment ID.
36 * @param int $src_x The start x position to crop from.
37 * @param int $src_y The start y position to crop from.
38 * @param int $src_w The width to crop.
39 * @param int $src_h The height to crop.
40 * @param int $dst_w The destination width.
41 * @param int $dst_h The destination height.
42 * @param int $src_abs Optional. If the source crop points are absolute.
43 * @param string $dst_file Optional. The destination file to write to.
44 * @return string|WP_Error|false New filepath on success, WP_Error or false on failure.
46 function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
47 if ( is_numeric( $src ) ) { // Handle int as attachment ID
48 $src_file = get_attached_file( $src );
49 if ( ! file_exists( $src_file ) ) {
50 // If the file doesn't exist, attempt a url fopen on the src link.
51 // This can occur with certain file replication plugins.
52 $post = get_post( $src );
53 $image_type = $post->post_mime_type;
54 $src = load_image_to_edit( $src, $post->post_mime_type, 'full' );
56 $size = @getimagesize( $src_file );
57 $image_type = ( $size ) ? $size['mime'] : '';
58 $src = wp_load_image( $src_file );
61 $size = @getimagesize( $src );
62 $image_type = ( $size ) ? $size['mime'] : '';
63 $src = wp_load_image( $src );
66 if ( ! is_resource( $src ) )
67 return new WP_Error( 'error_loading_image', $src, $src_file );
69 $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
76 if ( function_exists( 'imageantialias' ) )
77 imageantialias( $dst, true );
79 imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
81 imagedestroy( $src ); // Free up memory
84 $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
86 if ( 'image/png' != $image_type )
87 $dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
89 // The directory containing the original file may no longer exist when
90 // using a replication plugin.
91 wp_mkdir_p( dirname( $dst_file ) );
93 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
95 if ( 'image/png' == $image_type && imagepng( $dst, $dst_file ) )
97 elseif ( imagejpeg( $dst, $dst_file, apply_filters( 'jpeg_quality', 90, 'wp_crop_image' ) ) )
104 * Generate post thumbnail attachment meta data.
108 * @param int $attachment_id Attachment Id to process.
109 * @param string $file Filepath of the Attached image.
110 * @return mixed Metadata for attachment.
112 function wp_generate_attachment_metadata( $attachment_id, $file ) {
113 $attachment = get_post( $attachment_id );
116 if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
117 $imagesize = getimagesize( $file );
118 $metadata['width'] = $imagesize[0];
119 $metadata['height'] = $imagesize[1];
120 list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96);
121 $metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
123 // Make the file path relative to the upload dir
124 $metadata['file'] = _wp_relative_upload_path($file);
126 // make thumbnails and other intermediate sizes
127 global $_wp_additional_image_sizes;
129 foreach ( get_intermediate_image_sizes() as $s ) {
130 $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false );
131 if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
132 $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
134 $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
135 if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
136 $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
138 $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
139 if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
140 $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes
142 $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
145 $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
147 foreach ($sizes as $size => $size_data ) {
148 $resized = image_make_intermediate_size( $file, $size_data['width'], $size_data['height'], $size_data['crop'] );
150 $metadata['sizes'][$size] = $resized;
153 // fetch additional metadata from exif/iptc
154 $image_meta = wp_read_image_metadata( $file );
156 $metadata['image_meta'] = $image_meta;
160 return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
164 * Calculated the new dimensions for a downsampled image.
167 * @see wp_constrain_dimensions()
169 * @param int $width Current width of the image
170 * @param int $height Current height of the image
171 * @return mixed Array(height,width) of shrunk dimensions.
173 function get_udims( $width, $height) {
174 return wp_constrain_dimensions( $width, $height, 128, 96 );
178 * Convert a fraction string to a decimal.
185 function wp_exif_frac2dec($str) {
186 @list( $n, $d ) = explode( '/', $str );
193 * Convert the exif date format to a unix timestamp.
200 function wp_exif_date2ts($str) {
201 @list( $date, $time ) = explode( ' ', trim($str) );
202 @list( $y, $m, $d ) = explode( ':', $date );
204 return strtotime( "{$y}-{$m}-{$d} {$time}" );
208 * Get extended image metadata, exif or iptc as available.
210 * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
211 * created_timestamp, focal_length, shutter_speed, and title.
213 * The IPTC metadata that is retrieved is APP13, credit, byline, created date
214 * and time, caption, copyright, and title. Also includes FNumber, Model,
215 * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
217 * @todo Try other exif libraries if available.
220 * @param string $file
221 * @return bool|array False on failure. Image metadata array on success.
223 function wp_read_image_metadata( $file ) {
224 if ( ! file_exists( $file ) )
227 list( , , $sourceImageType ) = getimagesize( $file );
229 // exif contains a bunch of data we'll probably never need formatted in ways
230 // that are difficult to use. We'll normalize it and just extract the fields
231 // that are likely to be useful. Fractions and numbers are converted to
232 // floats, dates to unix timestamps, and everything else to strings.
238 'created_timestamp' => 0,
242 'shutter_speed' => 0,
246 // read iptc first, since it might contain data not available in exif such
247 // as caption, description etc
248 if ( is_callable( 'iptcparse' ) ) {
249 getimagesize( $file, $info );
251 if ( ! empty( $info['APP13'] ) ) {
252 $iptc = iptcparse( $info['APP13'] );
254 // headline, "A brief synopsis of the caption."
255 if ( ! empty( $iptc['2#105'][0] ) )
256 $meta['title'] = utf8_encode( trim( $iptc['2#105'][0] ) );
257 // title, "Many use the Title field to store the filename of the image, though the field may be used in many ways."
258 elseif ( ! empty( $iptc['2#005'][0] ) )
259 $meta['title'] = utf8_encode( trim( $iptc['2#005'][0] ) );
261 if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption
262 $caption = utf8_encode( trim( $iptc['2#120'][0] ) );
263 if ( empty( $meta['title'] ) ) {
264 // Assume the title is stored in 2:120 if it's short.
265 if ( strlen( $caption ) < 80 )
266 $meta['title'] = $caption;
268 $meta['caption'] = $caption;
269 } elseif ( $caption != $meta['title'] ) {
270 $meta['caption'] = $caption;
274 if ( ! empty( $iptc['2#110'][0] ) ) // credit
275 $meta['credit'] = utf8_encode(trim($iptc['2#110'][0]));
276 elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline
277 $meta['credit'] = utf8_encode(trim($iptc['2#080'][0]));
279 if ( ! empty( $iptc['2#055'][0] ) and ! empty( $iptc['2#060'][0] ) ) // created date and time
280 $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] );
282 if ( ! empty( $iptc['2#116'][0] ) ) // copyright
283 $meta['copyright'] = utf8_encode( trim( $iptc['2#116'][0] ) );
287 // fetch additional info from exif if available
288 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 ) ) ) ) {
289 $exif = @exif_read_data( $file );
291 if ( !empty( $exif['Title'] ) )
292 $meta['title'] = utf8_encode( trim( $exif['Title'] ) );
294 if ( ! empty( $exif['ImageDescription'] ) ) {
295 if ( empty( $meta['title'] ) && strlen( $exif['ImageDescription'] ) < 80 ) {
296 // Assume the title is stored in ImageDescription
297 $meta['title'] = utf8_encode( trim( $exif['ImageDescription'] ) );
298 if ( ! empty( $exif['COMPUTED']['UserComment'] ) && trim( $exif['COMPUTED']['UserComment'] ) != $meta['title'] )
299 $meta['caption'] = utf8_encode( trim( $exif['COMPUTED']['UserComment'] ) );
300 } elseif ( trim( $exif['ImageDescription'] ) != $meta['title'] ) {
301 $meta['caption'] = utf8_encode( trim( $exif['ImageDescription'] ) );
303 } elseif ( ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) {
304 $meta['caption'] = utf8_encode( trim( $exif['Comments'] ) );
307 if ( ! empty( $exif['Artist'] ) )
308 $meta['credit'] = utf8_encode( trim( $exif['Artist'] ) );
309 elseif ( ! empty($exif['Author'] ) )
310 $meta['credit'] = utf8_encode( trim( $exif['Author'] ) );
312 if ( ! empty( $exif['Copyright'] ) )
313 $meta['copyright'] = utf8_encode( trim( $exif['Copyright'] ) );
314 if ( ! empty($exif['FNumber'] ) )
315 $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
316 if ( ! empty($exif['Model'] ) )
317 $meta['camera'] = utf8_encode( trim( $exif['Model'] ) );
318 if ( ! empty($exif['DateTimeDigitized'] ) )
319 $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized'] );
320 if ( ! empty($exif['FocalLength'] ) )
321 $meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] );
322 if ( ! empty($exif['ISOSpeedRatings'] ) ) {
323 $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings'];
324 $meta['iso'] = utf8_encode( trim( $meta['iso'] ) );
326 if ( ! empty($exif['ExposureTime'] ) )
327 $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
330 return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
335 * Validate that file is an image.
339 * @param string $path File path to test if valid image.
340 * @return bool True if valid image, false if not valid image.
342 function file_is_valid_image($path) {
343 $size = @getimagesize($path);
344 return !empty($size);
348 * Validate that file is suitable for displaying within a web page.
351 * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path.
353 * @param string $path File path to test.
354 * @return bool True if suitable, false if not suitable.
356 function file_is_displayable_image($path) {
357 $info = @getimagesize($path);
360 elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed
365 return apply_filters('file_is_displayable_image', $result, $path);
369 * Load an image resource for editing.
373 * @param string $attachment_id Attachment ID.
374 * @param string $mime_type Image mime type.
375 * @param string $size Optional. Image size, defaults to 'full'.
376 * @return resource|false The resulting image resource on success, false on failure.
378 function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
379 $filepath = _load_image_to_edit_path( $attachment_id, $size );
380 if ( empty( $filepath ) )
383 switch ( $mime_type ) {
385 $image = imagecreatefromjpeg($filepath);
388 $image = imagecreatefrompng($filepath);
391 $image = imagecreatefromgif($filepath);
397 if ( is_resource($image) ) {
398 $image = apply_filters('load_image_to_edit', $image, $attachment_id, $size);
399 if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
400 imagealphablending($image, false);
401 imagesavealpha($image, true);
408 * Retrieve the path or url of an attachment's attached file.
410 * If the attached file is not present on the local filesystem (usually due to replication plugins),
411 * then the url of the file is returned if url fopen is supported.
416 * @param string $attachment_id Attachment ID.
417 * @param string $size Optional. Image size, defaults to 'full'.
418 * @return string|false File path or url on success, false on failure.
420 function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
421 $filepath = get_attached_file( $attachment_id );
423 if ( $filepath && file_exists( $filepath ) ) {
424 if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
425 $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
427 } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) {
428 $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
431 return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
435 * Copy an existing image file.
440 * @param string $attachment_id Attachment ID.
441 * @return string|false New file path on success, false on failure.
443 function _copy_image_file( $attachment_id ) {
444 $dst_file = $src_file = get_attached_file( $attachment_id );
445 if ( ! file_exists( $src_file ) )
446 $src_file = _load_image_to_edit_path( $attachment_id );
449 $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
450 $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
452 // The directory containing the original file may no longer exist when
453 // using a replication plugin.
454 wp_mkdir_p( dirname( $dst_file ) );
456 if ( ! @copy( $src_file, $dst_file ) )