[ Index ]

PHP Cross Reference of WordPress

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   * @subpackage Administration
   7   */
   8  
   9  /**
  10   * Create a thumbnail from an Image given a maximum side size.
  11   *
  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.
  15   *
  16   * @since 1.2.0
  17   *
  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.
  22   */
  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 );
  28  }
  29  
  30  /**
  31   * Crop an Image to a given size.
  32   *
  33   * @since 2.1.0
  34   *
  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.
  45   */
  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' );
  55          } else {
  56              $size = @getimagesize( $src_file );
  57              $image_type = ( $size ) ? $size['mime'] : '';
  58              $src = wp_load_image( $src_file );
  59          }
  60      } else {
  61          $size = @getimagesize( $src );
  62          $image_type = ( $size ) ? $size['mime'] : '';
  63          $src = wp_load_image( $src );
  64      }
  65  
  66      if ( ! is_resource( $src ) )
  67          return new WP_Error( 'error_loading_image', $src, $src_file );
  68  
  69      $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
  70  
  71      if ( $src_abs ) {
  72          $src_w -= $src_x;
  73          $src_h -= $src_y;
  74      }
  75  
  76      if ( function_exists( 'imageantialias' ) )
  77          imageantialias( $dst, true );
  78  
  79      imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  80  
  81      imagedestroy( $src ); // Free up memory
  82  
  83      if ( ! $dst_file )
  84          $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file );
  85  
  86      if ( 'image/png' != $image_type )
  87          $dst_file = preg_replace( '/\\.[^\\.]+$/', '.jpg', $dst_file );
  88  
  89      // The directory containing the original file may no longer exist when
  90      // using a replication plugin.
  91      wp_mkdir_p( dirname( $dst_file ) );
  92  
  93      $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) );
  94  
  95      if ( 'image/png' == $image_type && imagepng( $dst, $dst_file ) )
  96          return $dst_file;
  97      elseif ( imagejpeg( $dst, $dst_file, apply_filters( 'jpeg_quality', 90, 'wp_crop_image' ) ) )
  98          return $dst_file;
  99      else
 100          return false;
 101  }
 102  
 103  /**
 104   * Generate post thumbnail attachment meta data.
 105   *
 106   * @since 2.1.0
 107   *
 108   * @param int $attachment_id Attachment Id to process.
 109   * @param string $file Filepath of the Attached image.
 110   * @return mixed Metadata for attachment.
 111   */
 112  function wp_generate_attachment_metadata( $attachment_id, $file ) {
 113      $attachment = get_post( $attachment_id );
 114  
 115      $metadata = array();
 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'";
 122  
 123          // Make the file path relative to the upload dir
 124          $metadata['file'] = _wp_relative_upload_path($file);
 125  
 126          // make thumbnails and other intermediate sizes
 127          global $_wp_additional_image_sizes;
 128  
 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
 133              else
 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
 137              else
 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
 141              else
 142                  $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
 143          }
 144  
 145          $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
 146  
 147          foreach ($sizes as $size => $size_data ) {
 148              $resized = image_make_intermediate_size( $file, $size_data['width'], $size_data['height'], $size_data['crop'] );
 149              if ( $resized )
 150                  $metadata['sizes'][$size] = $resized;
 151          }
 152  
 153          // fetch additional metadata from exif/iptc
 154          $image_meta = wp_read_image_metadata( $file );
 155          if ( $image_meta )
 156              $metadata['image_meta'] = $image_meta;
 157  
 158      }
 159  
 160      return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id );
 161  }
 162  
 163  /**
 164   * Calculated the new dimensions for a downsampled image.
 165   *
 166   * @since 2.0.0
 167   * @see wp_constrain_dimensions()
 168   *
 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.
 172   */
 173  function get_udims( $width, $height) {
 174      return wp_constrain_dimensions( $width, $height, 128, 96 );
 175  }
 176  
 177  /**
 178   * Convert a fraction string to a decimal.
 179   *
 180   * @since 2.5.0
 181   *
 182   * @param string $str
 183   * @return int|float
 184   */
 185  function wp_exif_frac2dec($str) {
 186      @list( $n, $d ) = explode( '/', $str );
 187      if ( !empty($d) )
 188          return $n / $d;
 189      return $str;
 190  }
 191  
 192  /**
 193   * Convert the exif date format to a unix timestamp.
 194   *
 195   * @since 2.5.0
 196   *
 197   * @param string $str
 198   * @return int
 199   */
 200  function wp_exif_date2ts($str) {
 201      @list( $date, $time ) = explode( ' ', trim($str) );
 202      @list( $y, $m, $d ) = explode( ':', $date );
 203  
 204      return strtotime( "{$y}-{$m}-{$d} {$time}" );
 205  }
 206  
 207  /**
 208   * Get extended image metadata, exif or iptc as available.
 209   *
 210   * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso
 211   * created_timestamp, focal_length, shutter_speed, and title.
 212   *
 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.
 216   *
 217   * @todo Try other exif libraries if available.
 218   * @since 2.5.0
 219   *
 220   * @param string $file
 221   * @return bool|array False on failure. Image metadata array on success.
 222   */
 223  function wp_read_image_metadata( $file ) {
 224      if ( ! file_exists( $file ) )
 225          return false;
 226  
 227      list( , , $sourceImageType ) = getimagesize( $file );
 228  
 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.
 233      $meta = array(
 234          'aperture' => 0,
 235          'credit' => '',
 236          'camera' => '',
 237          'caption' => '',
 238          'created_timestamp' => 0,
 239          'copyright' => '',
 240          'focal_length' => 0,
 241          'iso' => 0,
 242          'shutter_speed' => 0,
 243          'title' => '',
 244      );
 245  
 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 );
 250  
 251          if ( ! empty( $info['APP13'] ) ) {
 252              $iptc = iptcparse( $info['APP13'] );
 253  
 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] ) );
 260  
 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;
 267                      else
 268                          $meta['caption'] = $caption;
 269                  } elseif ( $caption != $meta['title'] ) {
 270                      $meta['caption'] = $caption;
 271                  }
 272              }
 273  
 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]));
 278  
 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  
 282              if ( ! empty( $iptc['2#116'][0] ) ) // copyright
 283                  $meta['copyright'] = utf8_encode( trim( $iptc['2#116'][0] ) );
 284           }
 285      }
 286  
 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 );
 290  
 291          if ( !empty( $exif['Title'] ) )
 292              $meta['title'] = utf8_encode( trim( $exif['Title'] ) );
 293  
 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'] ) );
 302              }
 303          } elseif ( ! empty( $exif['Comments'] ) && trim( $exif['Comments'] ) != $meta['title'] ) {
 304              $meta['caption'] = utf8_encode( trim( $exif['Comments'] ) );
 305          }
 306  
 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'] ) );
 311  
 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'] = utf8_encode( trim( $exif['ISOSpeedRatings'] ) );
 324          if ( ! empty($exif['ExposureTime'] ) )
 325              $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] );
 326      }
 327  
 328      return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType );
 329  
 330  }
 331  
 332  /**
 333   * Validate that file is an image.
 334   *
 335   * @since 2.5.0
 336   *
 337   * @param string $path File path to test if valid image.
 338   * @return bool True if valid image, false if not valid image.
 339   */
 340  function file_is_valid_image($path) {
 341      $size = @getimagesize($path);
 342      return !empty($size);
 343  }
 344  
 345  /**
 346   * Validate that file is suitable for displaying within a web page.
 347   *
 348   * @since 2.5.0
 349   * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path.
 350   *
 351   * @param string $path File path to test.
 352   * @return bool True if suitable, false if not suitable.
 353   */
 354  function file_is_displayable_image($path) {
 355      $info = @getimagesize($path);
 356      if ( empty($info) )
 357          $result = false;
 358      elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) )    // only gif, jpeg and png images can reliably be displayed
 359          $result = false;
 360      else
 361          $result = true;
 362  
 363      return apply_filters('file_is_displayable_image', $result, $path);
 364  }
 365  
 366  /**
 367   * Load an image resource for editing.
 368   *
 369   * @since 2.9.0
 370   *
 371   * @param string $attachment_id Attachment ID.
 372   * @param string $mime_type Image mime type.
 373   * @param string $size Optional. Image size, defaults to 'full'.
 374   * @return resource|false The resulting image resource on success, false on failure.
 375   */
 376  function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) {
 377      $filepath = _load_image_to_edit_path( $attachment_id, $size );
 378      if ( empty( $filepath ) )
 379          return false;
 380  
 381      switch ( $mime_type ) {
 382          case 'image/jpeg':
 383              $image = imagecreatefromjpeg($filepath);
 384              break;
 385          case 'image/png':
 386              $image = imagecreatefrompng($filepath);
 387              break;
 388          case 'image/gif':
 389              $image = imagecreatefromgif($filepath);
 390              break;
 391          default:
 392              $image = false;
 393              break;
 394      }
 395      if ( is_resource($image) ) {
 396          $image = apply_filters('load_image_to_edit', $image, $attachment_id, $size);
 397          if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
 398              imagealphablending($image, false);
 399              imagesavealpha($image, true);
 400          }
 401      }
 402      return $image;
 403  }
 404  
 405  /**
 406   * Retrieve the path or url of an attachment's attached file.
 407   *
 408   * If the attached file is not present on the local filesystem (usually due to replication plugins),
 409   * then the url of the file is returned if url fopen is supported.
 410   *
 411   * @since 3.4.0
 412   * @access private
 413   *
 414   * @param string $attachment_id Attachment ID.
 415   * @param string $size Optional. Image size, defaults to 'full'.
 416   * @return string|false File path or url on success, false on failure.
 417   */
 418  function _load_image_to_edit_path( $attachment_id, $size = 'full' ) {
 419      $filepath = get_attached_file( $attachment_id );
 420  
 421      if ( $filepath && file_exists( $filepath ) ) {
 422          if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) {
 423              $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size );
 424          }
 425      } elseif ( function_exists( 'fopen' ) && function_exists( 'ini_get' ) && true == ini_get( 'allow_url_fopen' ) ) {
 426          $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size );
 427      }
 428  
 429      return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size );
 430  }
 431  
 432  /**
 433   * Copy an existing image file.
 434   *
 435   * @since 3.4.0
 436   * @access private
 437   *
 438   * @param string $attachment_id Attachment ID.
 439   * @return string|false New file path on success, false on failure.
 440   */
 441  function _copy_image_file( $attachment_id ) {
 442      $dst_file = $src_file = get_attached_file( $attachment_id );
 443      if ( ! file_exists( $src_file ) ) 
 444          $src_file = _load_image_to_edit_path( $attachment_id );
 445  
 446      if ( $src_file ) {
 447          $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file );
 448          $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) ); 
 449          if ( ! @copy( $src_file, $dst_file ) )
 450              $dst_file = false;
 451      } else {
 452          $dst_file = false;
 453      }
 454  
 455      return $dst_file;
 456  }


Generated: Fri May 25 03:56:23 2012 Hosted by follow the white rabbit.