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 * @return string Thumbnail path on success, Error string on failure.
22 function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) {
23 $thumbpath = image_resize( $file, $max_side, $max_side );
24 return apply_filters( 'wp_create_thumbnail', $thumbpath );
28 * Crop an Image to a given size.
32 * @param string|int $src_file The source file or Attachment ID.
33 * @param int $src_x The start x position to crop from.
34 * @param int $src_y The start y position to crop from.
35 * @param int $src_w The width to crop.
36 * @param int $src_h The height to crop.
37 * @param int $dst_w The destination width.
38 * @param int $dst_h The destination height.
39 * @param int $src_abs Optional. If the source crop points are absolute.
40 * @param string $dst_file Optional. The destination file to write to.
41 * @return string New filepath on success, String error message on failure.
43 function wp_crop_image( $src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
44 if ( is_numeric( $src_file ) ) // Handle int as attachment ID
45 $src_file = get_attached_file( $src_file );
47 $src = wp_load_image( $src_file );
49 if ( !is_resource( $src ))
52 $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
59 if (function_exists('imageantialias'))
60 imageantialias( $dst, true );
62 imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
64 imagedestroy( $src ); // Free up memory
67 $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
69 $dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
71 if ( imagejpeg( $dst, $dst_file, apply_filters( 'jpeg_quality', 90, 'wp_crop_image' ) ) )
78 * Generate post thumbnail attachment meta data.
82 * @param int $attachment_id Attachment Id to process.
83 * @param string $file Filepath of the Attached image.
84 * @return mixed Metadata for attachment.
86 function wp_generate_attachment_metadata( $attachment_id, $file ) {
87 $attachment = get_post( $attachment_id );
90 if ( preg_match('!^image/!', get_post_mime_type( $attachment )) && file_is_displayable_image($file) ) {
91 $imagesize = getimagesize( $file );
92 $metadata['width'] = $imagesize[0];
93 $metadata['height'] = $imagesize[1];
94 list($uwidth, $uheight) = wp_shrink_dimensions($metadata['width'], $metadata['height']);
95 $metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
97 // Make the file path relative to the upload dir
98 $metadata['file'] = _wp_relative_upload_path($file);
100 // make thumbnails and other intermediate sizes
101 global $_wp_additional_image_sizes;
102 $temp_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
103 if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
104 $temp_sizes = array_merge( $temp_sizes, array_keys( $_wp_additional_image_sizes ) );
106 $temp_sizes = apply_filters( 'intermediate_image_sizes', $temp_sizes );
108 foreach ( $temp_sizes as $s ) {
109 $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => FALSE );
110 if ( isset( $_wp_additional_image_sizes[$s]['width'] ) )
111 $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); // For theme-added sizes
113 $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
114 if ( isset( $_wp_additional_image_sizes[$s]['height'] ) )
115 $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); // For theme-added sizes
117 $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
118 if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) )
119 $sizes[$s]['crop'] = intval( $_wp_additional_image_sizes[$s]['crop'] ); // For theme-added sizes
121 $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
124 $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
126 foreach ($sizes as $size => $size_data ) {
127 $resized = image_make_intermediate_size( $file, $size_data['width'], $size_data['height'], $size_data['crop'] );
129 $metadata['sizes'][$size] = $resized;
132 // fetch additional metadata from exif/iptc
133 $image_meta = wp_read_image_metadata( $file );
135 $metadata['image_meta'] = $image_meta;
139 return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
143 * Load an image from a string, if PHP supports it.
147 * @param string $file Filename of the image to load.
148 * @return resource The resulting image resource on success, Error string on failure.
150 function wp_load_image( $file ) {
151 if ( is_numeric( $file ) )
152 $file = get_attached_file( $file );
154 if ( ! file_exists( $file ) )
155 return sprintf(__('File “%s” doesn’t exist?'), $file);
157 if ( ! function_exists('imagecreatefromstring') )
158 return __('The GD image library is not installed.');
160 // Set artificially high because GD uses uncompressed images in memory
161 @ini_set('memory_limit', '256M');
162 $image = imagecreatefromstring( file_get_contents( $file ) );
164 if ( !is_resource( $image ) )
165 return sprintf(__('File “%s” is not an image.'), $file);
171 * Calculated the new dimentions for a downsampled image.
174 * @see wp_shrink_dimensions()
176 * @param int $width Current width of the image
177 * @param int $height Current height of the image
178 * @return mixed Array(height,width) of shrunk dimensions.
180 function get_udims( $width, $height) {
181 return wp_shrink_dimensions( $width, $height );
185 * Calculates the new dimentions for a downsampled image.
188 * @see wp_constrain_dimensions()
190 * @param int $width Current width of the image
191 * @param int $height Current height of the image
192 * @param int $wmax Maximum wanted width
193 * @param int $hmax Maximum wanted height
194 * @return mixed Array(height,width) of shrunk dimensions.
196 function wp_shrink_dimensions( $width, $height, $wmax = 128, $hmax = 96 ) {
197 return wp_constrain_dimensions( $width, $height, $wmax, $hmax );
201 * Convert a fraction string to a decimal.
208 function wp_exif_frac2dec($str) {
209 @list( $n, $d ) = explode( '/', $str );
216 * Convert the exif date format to a unix timestamp.
223 function wp_exif_date2ts($str) {
224 @list( $date, $time ) = explode( ' ', trim($str) );
225 @list( $y, $m, $d ) = explode( ':', $date );
227 return strtotime( "{$y}-{$m}-{$d} {$time}" );
231 * Get extended image metadata, exif or iptc as available.
233 * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
234 * created_timestamp, focal_length, shutter_speed, and title.
236 * The IPTC metadata that is retrieved is APP13, credit, byline, created date
237 * and time, caption, copyright, and title. Also includes FNumber, Model,
238 * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime.
240 * @todo Try other exif libraries if available.
243 * @param string $file
244 * @return bool|array False on failure. Image metadata array on success.
246 function wp_read_image_metadata( $file ) {
247 if ( !file_exists( $file ) )
250 list(,,$sourceImageType) = getimagesize( $file );
252 // exif contains a bunch of data we'll probably never need formatted in ways
253 // that are difficult to use. We'll normalize it and just extract the fields
254 // that are likely to be useful. Fractions and numbers are converted to
255 // floats, dates to unix timestamps, and everything else to strings.
261 'created_timestamp' => 0,
265 'shutter_speed' => 0,
269 // read iptc first, since it might contain data not available in exif such
270 // as caption, description etc
271 if ( is_callable('iptcparse') ) {
272 getimagesize($file, $info);
273 if ( !empty($info['APP13']) ) {
274 $iptc = iptcparse($info['APP13']);
275 if ( !empty($iptc['2#110'][0]) ) // credit
276 $meta['credit'] = utf8_encode(trim($iptc['2#110'][0]));
277 elseif ( !empty($iptc['2#080'][0]) ) // byline
278 $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]);
281 if ( !empty($iptc['2#120'][0]) ) // caption
282 $meta['caption'] = utf8_encode(trim($iptc['2#120'][0]));
283 if ( !empty($iptc['2#116'][0]) ) // copyright
284 $meta['copyright'] = utf8_encode(trim($iptc['2#116'][0]));
285 if ( !empty($iptc['2#005'][0]) ) // title
286 $meta['title'] = utf8_encode(trim($iptc['2#005'][0]));
290 // fetch additional info from exif if available
291 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)) ) ) {
292 $exif = @exif_read_data( $file );
293 if (!empty($exif['FNumber']))
294 $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
295 if (!empty($exif['Model']))
296 $meta['camera'] = trim( $exif['Model'] );
297 if (!empty($exif['DateTimeDigitized']))
298 $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']);
299 if (!empty($exif['FocalLength']))
300 $meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] );
301 if (!empty($exif['ISOSpeedRatings']))
302 $meta['iso'] = $exif['ISOSpeedRatings'];
303 if (!empty($exif['ExposureTime']))
304 $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
307 return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
312 * Validate that file is an image.
316 * @param string $path File path to test if valid image.
317 * @return bool True if valid image, false if not valid image.
319 function file_is_valid_image($path) {
320 $size = @getimagesize($path);
321 return !empty($size);
325 * Validate that file is suitable for displaying within a web page.
328 * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path.
330 * @param string $path File path to test.
331 * @return bool True if suitable, false if not suitable.
333 function file_is_displayable_image($path) {
334 $info = @getimagesize($path);
337 elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed
342 return apply_filters('file_is_displayable_image', $result, $path);