]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/image.php
Wordpress 2.6.2
[autoinstalls/wordpress.git] / wp-admin / includes / image.php
1 <?php
2 /**
3  * File contains all the administration image manipulation functions.
4  *
5  * @package WordPress
6  */
7
8 /**
9  * wp_create_thumbnail() - Create a thumbnail from an Image given a maximum side size.
10  *
11  * @package WordPress
12  * @param       mixed   $file   Filename of the original image, Or attachment id
13  * @param       int             $max_side       Maximum length of a single side for the thumbnail
14  * @return      string                  Thumbnail path on success, Error string on failure
15  *
16  * This function can handle most image file formats which PHP supports.
17  * If PHP does not have the functionality to save in a file of the same format, the thumbnail will be created as a jpeg.
18  */
19 function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) {
20         
21         $thumbpath = image_resize( $file, $max_side, $max_side );
22         return apply_filters( 'wp_create_thumbnail', $thumbpath );
23 }
24
25 /**
26  * wp_crop_image() - Crop an Image to a given size.
27  *
28  * @package WordPress
29  * @internal Missing Long Description
30  * @param       int     $src_file       The source file
31  * @param       int     $src_x          The start x position to crop from
32  * @param       int     $src_y          The start y position to crop from
33  * @param       int     $src_w          The width to crop
34  * @param       int     $src_h          The height to crop
35  * @param       int     $dst_w          The destination width
36  * @param       int     $dst_h          The destination height
37  * @param       int     $src_abs        If the source crop points are absolute
38  * @param       int     $dst_file       The destination file to write to
39  * @return      string                  New filepath on success, String error message on failure
40  *
41  */
42 function wp_crop_image( $src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
43         if ( is_numeric( $src_file ) ) // Handle int as attachment ID
44                 $src_file = get_attached_file( $src_file );
45
46         $src = wp_load_image( $src_file );
47
48         if ( !is_resource( $src ))
49                 return $src;
50
51         $dst = imagecreatetruecolor( $dst_w, $dst_h );
52
53         if ( $src_abs ) {
54                 $src_w -= $src_x;
55                 $src_h -= $src_y;
56         }
57
58         if (function_exists('imageantialias'))
59                 imageantialias( $dst, true );
60
61         imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
62
63         imagedestroy( $src ); // Free up memory
64
65         if ( ! $dst_file )
66                 $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
67
68         $dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
69
70         if ( imagejpeg( $dst, $dst_file ) )
71                 return $dst_file;
72         else
73                 return false;
74 }
75
76 /**
77  * wp_generate_attachment_metadata() - Generate post Image attachment Metadata
78  *
79  * @package WordPress
80  * @internal Missing Long Description
81  * @param       int             $attachment_id  Attachment Id to process
82  * @param       string  $file   Filepath of the Attached image
83  * @return      mixed                   Metadata for attachment
84  *
85  */
86 function wp_generate_attachment_metadata( $attachment_id, $file ) {
87         $attachment = get_post( $attachment_id );
88
89         $metadata = array();
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'";
96                 $metadata['file'] = $file;
97
98                 // make thumbnails and other intermediate sizes
99                 $sizes = array('thumbnail', 'medium');
100                 $sizes = apply_filters('intermediate_image_sizes', $sizes);
101                 
102                 foreach ($sizes as $size) {
103                         $resized = image_make_intermediate_size( $file, get_option("{$size}_size_w"), get_option("{$size}_size_h"), get_option("{$size}_crop") );
104                         if ( $resized )
105                                 $metadata['sizes'][$size] = $resized;
106                 }
107                         
108                 // fetch additional metadata from exif/iptc
109                 $image_meta = wp_read_image_metadata( $file );
110                 if ($image_meta)
111                         $metadata['image_meta'] = $image_meta;
112
113         }
114         return apply_filters( 'wp_generate_attachment_metadata', $metadata );
115 }
116
117 /**
118  * wp_load_image() - Load an image which PHP Supports.
119  *
120  * @package WordPress
121  * @internal Missing Long Description
122  * @param       string  $file   Filename of the image to load
123  * @return      resource                The resulting image resource on success, Error string on failure.
124  *
125  */
126 function wp_load_image( $file ) {
127         if ( is_numeric( $file ) )
128                 $file = get_attached_file( $file );
129
130         if ( ! file_exists( $file ) )
131                 return sprintf(__("File '%s' doesn't exist?"), $file);
132
133         if ( ! function_exists('imagecreatefromstring') )
134                 return __('The GD image library is not installed.');
135
136         // Set artificially high because GD uses uncompressed images in memory
137         @ini_set('memory_limit', '256M');
138         $image = imagecreatefromstring( file_get_contents( $file ) );
139
140         if ( !is_resource( $image ) )
141                 return sprintf(__("File '%s' is not an image."), $file);
142
143         return $image;
144 }
145
146 /**
147  * get_udims() - Calculated the new dimentions for downsampled images
148  *
149  * @package WordPress
150  * @internal Missing Description
151  * @see wp_shrink_dimensions()
152  * @param       int             $width  Current width of the image
153  * @param       int     $height Current height of the image
154  * @return      mixed                   Array(height,width) of shrunk dimensions.
155  *
156  */
157 function get_udims( $width, $height) {
158         return wp_shrink_dimensions( $width, $height );
159 }
160 /**
161  * wp_shrink_dimensions() - Calculates the new dimentions for a downsampled image.
162  *
163  * @package WordPress
164  * @internal Missing Long Description
165  * @param       int             $width  Current width of the image
166  * @param       int     $height Current height of the image
167  * @param       int             $wmax   Maximum wanted width
168  * @param       int             $hmax   Maximum wanted height
169  * @return      mixed                   Array(height,width) of shrunk dimensions.
170  *
171  */
172 function wp_shrink_dimensions( $width, $height, $wmax = 128, $hmax = 96 ) {
173         return wp_constrain_dimensions( $width, $height, $wmax, $hmax );
174 }
175
176 // convert a fraction string to a decimal
177 function wp_exif_frac2dec($str) {
178         @list( $n, $d ) = explode( '/', $str );
179         if ( !empty($d) )
180                 return $n / $d;
181         return $str;
182 }
183
184 // convert the exif date format to a unix timestamp
185 function wp_exif_date2ts($str) {
186         // seriously, who formats a date like 'YYYY:MM:DD hh:mm:ss'?
187         @list( $date, $time ) = explode( ' ', trim($str) );
188         @list( $y, $m, $d ) = explode( ':', $date );
189
190         return strtotime( "{$y}-{$m}-{$d} {$time}" );
191 }
192
193 // get extended image metadata, exif or iptc as available
194 function wp_read_image_metadata( $file ) {
195         if ( !file_exists( $file ) )
196                 return false;
197
198         list(,,$sourceImageType) = getimagesize( $file );
199
200         // exif contains a bunch of data we'll probably never need formatted in ways that are difficult to use.
201         // We'll normalize it and just extract the fields that are likely to be useful.  Fractions and numbers
202         // are converted to floats, dates to unix timestamps, and everything else to strings.
203         $meta = array(
204                 'aperture' => 0,
205                 'credit' => '',
206                 'camera' => '',
207                 'caption' => '',
208                 'created_timestamp' => 0,
209                 'copyright' => '',
210                 'focal_length' => 0,
211                 'iso' => 0,
212                 'shutter_speed' => 0,
213                 'title' => '',
214         );
215
216         // read iptc first, since it might contain data not available in exif such as caption, description etc
217         if ( is_callable('iptcparse') ) {
218                 getimagesize($file, $info);
219                 if ( !empty($info['APP13']) ) {
220                         $iptc = iptcparse($info['APP13']);
221                         if ( !empty($iptc['2#110'][0]) ) // credit
222                                 $meta['credit'] = utf8_encode(trim($iptc['2#110'][0]));
223                         elseif ( !empty($iptc['2#080'][0]) ) // byline
224                                 $meta['credit'] = utf8_encode(trim($iptc['2#080'][0]));
225                         if ( !empty($iptc['2#055'][0]) and !empty($iptc['2#060'][0]) ) // created datee and time
226                                 $meta['created_timestamp'] = strtotime($iptc['2#055'][0] . ' ' . $iptc['2#060'][0]);
227                         if ( !empty($iptc['2#120'][0]) ) // caption
228                                 $meta['caption'] = utf8_encode(trim($iptc['2#120'][0]));
229                         if ( !empty($iptc['2#116'][0]) ) // copyright
230                                 $meta['copyright'] = utf8_encode(trim($iptc['2#116'][0]));
231                         if ( !empty($iptc['2#005'][0]) ) // title
232                                 $meta['title'] = utf8_encode(trim($iptc['2#005'][0]));
233                  }
234         }
235
236         // fetch additional info from exif if available
237         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)) ) ) {
238                 $exif = @exif_read_data( $file );
239                 if (!empty($exif['FNumber']))
240                         $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
241                 if (!empty($exif['Model']))
242                         $meta['camera'] = trim( $exif['Model'] );
243                 if (!empty($exif['DateTimeDigitized']))
244                         $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']);
245                 if (!empty($exif['FocalLength']))
246                         $meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] );
247                 if (!empty($exif['ISOSpeedRatings']))
248                         $meta['iso'] = $exif['ISOSpeedRatings'];
249                 if (!empty($exif['ExposureTime']))
250                         $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
251         }
252         // FIXME: try other exif libraries if available
253
254         return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
255
256 }
257
258 // is the file a real image file?
259 function file_is_valid_image($path) {
260         $size = @getimagesize($path);
261         return !empty($size);
262 }
263
264 // is the file an image suitable for displaying within a web page?
265 function file_is_displayable_image($path) {
266         $info = @getimagesize($path);
267         if ( empty($info) )
268                 $result = false;
269         elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) )
270                 // only gif, jpeg and png images can reliably be displayed
271                 $result = false;
272         elseif ( $info['channels'] > 0 && $info['channels'] != 3 ) {
273                 // some web browsers can't display cmyk or grayscale jpegs
274                 $result = false;
275         }
276         else
277                 $result = true;
278                 
279         return apply_filters('file_is_displayable_image', $result, $path);
280 }
281
282 ?>