PHP Cross Reference of WordPress Subversion HEAD

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]

title

Body

[close]

/wp-admin/includes/ -> image.php (source)

   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      if ( ctype_digit( $file ) ) // Handle int as attachment ID
  21          $file = get_attached_file( $file );
  22  
  23      $image = wp_load_image( $file );
  24      
  25      if ( !is_resource( $image ) )
  26          return $image;
  27  
  28      list($sourceImageWidth, $sourceImageHeight, $sourceImageType) = getimagesize( $file );
  29  
  30      if ( function_exists( 'imageantialias' ))
  31          imageantialias( $image, true );
  32  
  33      list($image_new_width, $image_new_height) = wp_shrink_dimensions( $sourceImageWidth, $sourceImageHeight, $max_side, $max_side);
  34  
  35      $thumbnail = imagecreatetruecolor( $image_new_width, $image_new_height);
  36      @ imagecopyresampled( $thumbnail, $image, 0, 0, 0, 0, $image_new_width, $image_new_height, $sourceImageWidth, $sourceImageHeight );
  37  
  38      imagedestroy( $image ); // Free up memory 
  39  
  40      // If no filters change the filename, we'll do a default transformation.
  41      if ( basename( $file ) == $thumb = apply_filters( 'thumbnail_filename', basename( $file ) ) )
  42          $thumb = preg_replace( '!(\.[^.]+)?$!', '.thumbnail$1', basename( $file ), 1 );
  43  
  44      $thumbpath = str_replace( basename( $file ), $thumb, $file );
  45  
  46      switch( $sourceImageType ){
  47          default: // We'll create a Jpeg if we cant use its native file format
  48              $thumb = preg_replace( '/\\.[^\\.]+$/', '.jpg', $thumb ); //Change file extension to Jpg
  49          case IMAGETYPE_JPEG:
  50              if (!imagejpeg( $thumbnail, $thumbpath ) )
  51                  return __( 'Thumbnail path invalid' );
  52              break;
  53          case IMAGETYPE_GIF:
  54              if (!imagegif( $thumbnail, $thumbpath ) )
  55                  return __( 'Thumbnail path invalid' );
  56              break;
  57          case IMAGETYPE_PNG:
  58              if (!imagepng( $thumbnail, $thumbpath ) )
  59                  return __( 'Thumbnail path invalid' );
  60              break;
  61      }
  62  
  63      imagedestroy( $thumbnail ); // Free up memory 
  64      
  65      // Set correct file permissions 
  66      $stat = stat( dirname( $thumbpath )); 
  67      $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
  68      @ chmod( $thumbpath, $perms ); 
  69  
  70      return apply_filters( 'wp_create_thumbnail', $thumbpath );
  71  }
  72  
  73  /**
  74   * wp_crop_image() - Crop an Image to a given size.
  75   *
  76   * @package WordPress
  77   * @internal Missing Long Description
  78   * @param    int    $src_file    The source file
  79   * @param    int    $src_x        The start x position to crop from
  80   * @param    int    $src_y        The start y position to crop from
  81   * @param    int    $src_w        The width to crop
  82   * @param    int    $src_h        The height to crop
  83   * @param    int    $dst_w        The destination width
  84   * @param    int    $dst_h        The destination height
  85   * @param    int    $src_abs    If the source crop points are absolute
  86   * @param    int    $dst_file    The destination file to write to
  87   * @return    string            New filepath on success, String error message on failure
  88   *
  89   */
  90  function wp_crop_image( $src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
  91      if ( ctype_digit( $src_file ) ) // Handle int as attachment ID
  92          $src_file = get_attached_file( $src_file );
  93  
  94      $src = wp_load_image( $src_file );
  95  
  96      if ( !is_resource( $src ))
  97          return $src;
  98  
  99      $dst = imagecreatetruecolor( $dst_w, $dst_h );
 100  
 101      if ( $src_abs ) {
 102          $src_w -= $src_x;
 103          $src_h -= $src_y;
 104      }
 105  
 106      if (function_exists('imageantialias'))
 107          imageantialias( $dst, true );
 108  
 109      imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
 110      
 111      imagedestroy( $src ); // Free up memory 
 112  
 113      if ( ! $dst_file )
 114          $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
 115  
 116      $dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
 117  
 118      if ( imagejpeg( $dst, $dst_file ) )
 119          return $dst_file;
 120      else
 121          return false;
 122  }
 123  
 124  /**
 125   * wp_generate_attachment_metadata() - Generate post Image attachment Metadata
 126   *
 127   * @package WordPress
 128   * @internal Missing Long Description
 129   * @param    int        $attachment_id    Attachment Id to process
 130   * @param    string    $file    Filepath of the Attached image
 131   * @return    mixed            Metadata for attachment
 132   *
 133   */
 134  function wp_generate_attachment_metadata( $attachment_id, $file ) {
 135      $attachment = get_post( $attachment_id );
 136  
 137      $metadata = array();
 138      if ( preg_match('!^image/!', get_post_mime_type( $attachment )) ) {
 139          $imagesize = getimagesize( $file );
 140          $metadata['width'] = $imagesize[0];
 141          $metadata['height'] = $imagesize[1];
 142          list($uwidth, $uheight) = wp_shrink_dimensions($metadata['width'], $metadata['height']);
 143          $metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
 144          $metadata['file'] = $file;
 145  
 146          $max = apply_filters( 'wp_thumbnail_creation_size_limit', 3 * 1024 * 1024, $attachment_id, $file );
 147  
 148          if ( $max < 0 || $metadata['width'] * $metadata['height'] < $max ) {
 149              $max_side = apply_filters( 'wp_thumbnail_max_side_length', 128, $attachment_id, $file );
 150              $thumb = wp_create_thumbnail( $file, $max_side );
 151  
 152              if ( @file_exists($thumb) )
 153                  $metadata['thumb'] = basename($thumb);
 154          }
 155          
 156          // fetch additional metadata from exif/iptc
 157          $image_meta = wp_read_image_metadata( $file );
 158          if ($image_meta)
 159              $metadata['image_meta'] = $image_meta;
 160  
 161      }
 162      return apply_filters( 'wp_generate_attachment_metadata', $metadata );
 163  }
 164  
 165  /**
 166   * wp_load_image() - Load an image which PHP Supports.
 167   *
 168   * @package WordPress
 169   * @internal Missing Long Description
 170   * @param    string    $file    Filename of the image to load
 171   * @return    resource        The resulting image resource on success, Error string on failure.
 172   *
 173   */
 174  function wp_load_image( $file ) {
 175      if ( ctype_digit( $file ) )
 176          $file = get_attached_file( $file );
 177  
 178      if ( ! file_exists( $file ) )
 179          return sprintf(__("File '%s' doesn't exist?"), $file);
 180  
 181      if ( ! function_exists('imagecreatefromstring') )
 182          return __('The GD image library is not installed.');
 183  
 184      $image = @imagecreatefromstring( @file_get_contents( $file ) );
 185  
 186      if ( !is_resource( $image ) )
 187          return sprintf(__("File '%s' is not an image."), $file);
 188  
 189      return $image;
 190  }
 191  
 192  /**
 193   * get_udims() - Calculated the new dimentions for downsampled images
 194   *
 195   * @package WordPress
 196   * @internal Missing Description
 197   * @see wp_shrink_dimensions()
 198   * @param    int        $width    Current width of the image
 199   * @param    int     $height    Current height of the image
 200   * @return    mixed            Array(height,width) of shrunk dimensions.
 201   *
 202   */
 203  function get_udims( $width, $height) {
 204      return wp_shrink_dimensions( $width, $height );
 205  }
 206  /**
 207   * wp_shrink_dimensions() - Calculates the new dimentions for a downsampled image.
 208   *
 209   * @package WordPress
 210   * @internal Missing Long Description
 211   * @param    int        $width    Current width of the image
 212   * @param    int     $height    Current height of the image
 213   * @param    int        $wmax    Maximum wanted width
 214   * @param    int        $hmax    Maximum wanted height
 215   * @return    mixed            Array(height,width) of shrunk dimensions.
 216   *
 217   */
 218  function wp_shrink_dimensions( $width, $height, $wmax = 128, $hmax = 96 ) {
 219      if ( $height <= $hmax && $width <= $wmax ){
 220          //Image is smaller than max
 221          return array( $width, $height);
 222      } elseif ( $width / $height > $wmax / $hmax ) {
 223          //Image Width will be greatest
 224          return array( $wmax, (int) ($height / $width * $wmax ));
 225      } else {
 226          //Image Height will be greatest
 227          return array( (int) ($width / $height * $hmax ), $hmax );
 228      }
 229  }
 230  
 231  // convert a fraction string to a decimal
 232  function wp_exif_frac2dec($str) {
 233      @list( $n, $d ) = explode( '/', $str );
 234      if ( !empty($d) )
 235          return $n / $d;
 236      return $str;
 237  }
 238  
 239  // convert the exif date format to a unix timestamp
 240  function wp_exif_date2ts($str) {
 241      // seriously, who formats a date like 'YYYY:MM:DD hh:mm:ss'?
 242      @list( $date, $time ) = explode( ' ', trim($str) );
 243      @list( $y, $m, $d ) = explode( ':', $date );
 244  
 245      return strtotime( "{$y}-{$m}-{$d} {$time}" );
 246  }
 247  
 248  // get extended image metadata, exif or iptc as available
 249  function wp_read_image_metadata( $file ) {
 250      if ( !file_exists( $file ) )
 251          return false;
 252  
 253      // exif contains a bunch of data we'll probably never need formatted in ways that are difficult to use.
 254      // We'll normalize it and just extract the fields that are likely to be useful.  Fractions and numbers
 255      // are converted to floats, dates to unix timestamps, and everything else to strings.
 256      $meta = array(
 257          'aperture' => 0,
 258          'credit' => '',
 259          'camera' => '',
 260          'caption' => '',
 261          'created_timestamp' => 0,
 262          'copyright' => '',
 263          'focal_length' => 0,
 264          'iso' => 0,
 265          'shutter_speed' => 0,
 266          'title' => '',
 267      );
 268  
 269      // read iptc first, since it might contain data not available in exif such as caption, description etc
 270      if ( is_callable('iptcparse') ) {
 271          getimagesize($file, $info);
 272          if ( !empty($info['APP13']) ) {
 273              $iptc = iptcparse($info['APP13']);
 274              if ( !empty($iptc['2#110'][0]) ) // credit
 275                  $meta['credit'] = trim( $iptc['2#110'][0] );
 276              elseif ( !empty($iptc['2#080'][0]) ) // byline
 277                  $meta['credit'] = trim( $iptc['2#080'][0] );
 278              if ( !empty($iptc['2#055'][0]) and !empty($iptc['2#060'][0]) ) // created datee and time
 279                  $meta['created_timestamp'] = strtotime($iptc['2#055'][0] . ' ' . $iptc['2#060'][0]);
 280              if ( !empty($iptc['2#120'][0]) ) // caption
 281                  $meta['caption'] = trim( $iptc['2#120'][0] );
 282              if ( !empty($iptc['2#116'][0]) ) // copyright
 283                  $meta['copyright'] = trim( $iptc['2#116'][0] );
 284              if ( !empty($iptc['2#005'][0]) ) // title
 285                  $meta['title'] = trim( $iptc['2#005'][0] );
 286           }
 287      }
 288  
 289      // fetch additional info from exif if available
 290      if ( is_callable('exif_read_data') ) {
 291          $exif = exif_read_data( $file );
 292          if (!empty($exif['FNumber']))
 293              $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 );
 294          if (!empty($exif['Model']))
 295              $meta['camera'] = trim( $exif['Model'] );
 296          if (!empty($exif['DateTimeDigitized']))
 297              $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']);
 298          if (!empty($exif['FocalLength']))
 299              $meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] );
 300          if (!empty($exif['ISOSpeedRatings']))
 301              $meta['iso'] = $exif['ISOSpeedRatings'];
 302          if (!empty($exif['ExposureTime']))
 303              $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
 304      }
 305      // FIXME: try other exif libraries if available
 306  
 307      return apply_filters( 'wp_read_image_metadata', $meta, $file );
 308  
 309  }
 310  
 311  ?>


Generated Thu Dec 6 06:47:08 2007 for RedAlt XRefs Cross-referenced by PHPXref 0.6 and RedAlt