home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / class-wp-image-editor-gd.php < prev    next >
Encoding:
PHP Script  |  2017-08-22  |  12.6 KB  |  468 lines

  1. <?php
  2. /**
  3.  * WordPress GD Image Editor
  4.  *
  5.  * @package WordPress
  6.  * @subpackage Image_Editor
  7.  */
  8.  
  9. /**
  10.  * WordPress Image Editor Class for Image Manipulation through GD
  11.  *
  12.  * @since 3.5.0
  13.  *
  14.  * @see WP_Image_Editor
  15.  */
  16. class WP_Image_Editor_GD extends WP_Image_Editor {
  17.     /**
  18.      * GD Resource.
  19.      *
  20.      * @var resource
  21.      */
  22.     protected $image;
  23.  
  24.     public function __destruct() {
  25.         if ( $this->image ) {
  26.             // we don't need the original in memory anymore
  27.             imagedestroy( $this->image );
  28.         }
  29.     }
  30.  
  31.     /**
  32.      * Checks to see if current environment supports GD.
  33.      *
  34.      * @since 3.5.0
  35.      *
  36.      * @static
  37.      *
  38.      * @param array $args
  39.      * @return bool
  40.      */
  41.     public static function test( $args = array() ) {
  42.         if ( ! extension_loaded('gd') || ! function_exists('gd_info') )
  43.             return false;
  44.  
  45.         // On some setups GD library does not provide imagerotate() - Ticket #11536
  46.         if ( isset( $args['methods'] ) &&
  47.              in_array( 'rotate', $args['methods'] ) &&
  48.              ! function_exists('imagerotate') ){
  49.  
  50.                 return false;
  51.         }
  52.  
  53.         return true;
  54.     }
  55.  
  56.     /**
  57.      * Checks to see if editor supports the mime-type specified.
  58.      *
  59.      * @since 3.5.0
  60.      *
  61.      * @static
  62.      *
  63.      * @param string $mime_type
  64.      * @return bool
  65.      */
  66.     public static function supports_mime_type( $mime_type ) {
  67.         $image_types = imagetypes();
  68.         switch( $mime_type ) {
  69.             case 'image/jpeg':
  70.                 return ($image_types & IMG_JPG) != 0;
  71.             case 'image/png':
  72.                 return ($image_types & IMG_PNG) != 0;
  73.             case 'image/gif':
  74.                 return ($image_types & IMG_GIF) != 0;
  75.         }
  76.  
  77.         return false;
  78.     }
  79.  
  80.     /**
  81.      * Loads image from $this->file into new GD Resource.
  82.      *
  83.      * @since 3.5.0
  84.      *
  85.      * @return bool|WP_Error True if loaded successfully; WP_Error on failure.
  86.      */
  87.     public function load() {
  88.         if ( $this->image )
  89.             return true;
  90.  
  91.         if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) )
  92.             return new WP_Error( 'error_loading_image', __('File doesn’t exist?'), $this->file );
  93.  
  94.         // Set artificially high because GD uses uncompressed images in memory.
  95.         wp_raise_memory_limit( 'image' );
  96.  
  97.         $this->image = @imagecreatefromstring( file_get_contents( $this->file ) );
  98.  
  99.         if ( ! is_resource( $this->image ) )
  100.             return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file );
  101.  
  102.         $size = @getimagesize( $this->file );
  103.         if ( ! $size )
  104.             return new WP_Error( 'invalid_image', __('Could not read image size.'), $this->file );
  105.  
  106.         if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
  107.             imagealphablending( $this->image, false );
  108.             imagesavealpha( $this->image, true );
  109.         }
  110.  
  111.         $this->update_size( $size[0], $size[1] );
  112.         $this->mime_type = $size['mime'];
  113.  
  114.         return $this->set_quality();
  115.     }
  116.  
  117.     /**
  118.      * Sets or updates current image size.
  119.      *
  120.      * @since 3.5.0
  121.      *
  122.      * @param int $width
  123.      * @param int $height
  124.      * @return true
  125.      */
  126.     protected function update_size( $width = false, $height = false ) {
  127.         if ( ! $width )
  128.             $width = imagesx( $this->image );
  129.  
  130.         if ( ! $height )
  131.             $height = imagesy( $this->image );
  132.  
  133.         return parent::update_size( $width, $height );
  134.     }
  135.  
  136.     /**
  137.      * Resizes current image.
  138.      * Wraps _resize, since _resize returns a GD Resource.
  139.      *
  140.      * At minimum, either a height or width must be provided.
  141.      * If one of the two is set to null, the resize will
  142.      * maintain aspect ratio according to the provided dimension.
  143.      *
  144.      * @since 3.5.0
  145.      *
  146.      * @param  int|null $max_w Image width.
  147.      * @param  int|null $max_h Image height.
  148.      * @param  bool     $crop
  149.      * @return true|WP_Error
  150.      */
  151.     public function resize( $max_w, $max_h, $crop = false ) {
  152.         if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
  153.             return true;
  154.  
  155.         $resized = $this->_resize( $max_w, $max_h, $crop );
  156.  
  157.         if ( is_resource( $resized ) ) {
  158.             imagedestroy( $this->image );
  159.             $this->image = $resized;
  160.             return true;
  161.  
  162.         } elseif ( is_wp_error( $resized ) )
  163.             return $resized;
  164.  
  165.         return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
  166.     }
  167.  
  168.     /**
  169.      *
  170.      * @param int $max_w
  171.      * @param int $max_h
  172.      * @param bool|array $crop
  173.      * @return resource|WP_Error
  174.      */
  175.     protected function _resize( $max_w, $max_h, $crop = false ) {
  176.         $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
  177.         if ( ! $dims ) {
  178.             return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions'), $this->file );
  179.         }
  180.         list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
  181.  
  182.         $resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
  183.         imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  184.  
  185.         if ( is_resource( $resized ) ) {
  186.             $this->update_size( $dst_w, $dst_h );
  187.             return $resized;
  188.         }
  189.  
  190.         return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
  191.     }
  192.  
  193.     /**
  194.      * Resize multiple images from a single source.
  195.      *
  196.      * @since 3.5.0
  197.      *
  198.      * @param array $sizes {
  199.      *     An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
  200.      *
  201.      *     Either a height or width must be provided.
  202.      *     If one of the two is set to null, the resize will
  203.      *     maintain aspect ratio according to the provided dimension.
  204.      *
  205.      *     @type array $size {
  206.      *         Array of height, width values, and whether to crop.
  207.      *
  208.      *         @type int  $width  Image width. Optional if `$height` is specified.
  209.      *         @type int  $height Image height. Optional if `$width` is specified.
  210.      *         @type bool $crop   Optional. Whether to crop the image. Default false.
  211.      *     }
  212.      * }
  213.      * @return array An array of resized images' metadata by size.
  214.      */
  215.     public function multi_resize( $sizes ) {
  216.         $metadata = array();
  217.         $orig_size = $this->size;
  218.  
  219.         foreach ( $sizes as $size => $size_data ) {
  220.             if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
  221.                 continue;
  222.             }
  223.  
  224.             if ( ! isset( $size_data['width'] ) ) {
  225.                 $size_data['width'] = null;
  226.             }
  227.             if ( ! isset( $size_data['height'] ) ) {
  228.                 $size_data['height'] = null;
  229.             }
  230.  
  231.             if ( ! isset( $size_data['crop'] ) ) {
  232.                 $size_data['crop'] = false;
  233.             }
  234.  
  235.             $image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
  236.             $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
  237.  
  238.             if ( ! is_wp_error( $image ) && ! $duplicate ) {
  239.                 $resized = $this->_save( $image );
  240.  
  241.                 imagedestroy( $image );
  242.  
  243.                 if ( ! is_wp_error( $resized ) && $resized ) {
  244.                     unset( $resized['path'] );
  245.                     $metadata[$size] = $resized;
  246.                 }
  247.             }
  248.  
  249.             $this->size = $orig_size;
  250.         }
  251.  
  252.         return $metadata;
  253.     }
  254.  
  255.     /**
  256.      * Crops Image.
  257.      *
  258.      * @since 3.5.0
  259.      *
  260.      * @param int  $src_x   The start x position to crop from.
  261.      * @param int  $src_y   The start y position to crop from.
  262.      * @param int  $src_w   The width to crop.
  263.      * @param int  $src_h   The height to crop.
  264.      * @param int  $dst_w   Optional. The destination width.
  265.      * @param int  $dst_h   Optional. The destination height.
  266.      * @param bool $src_abs Optional. If the source crop points are absolute.
  267.      * @return bool|WP_Error
  268.      */
  269.     public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
  270.         // If destination width/height isn't specified, use same as
  271.         // width/height from source.
  272.         if ( ! $dst_w )
  273.             $dst_w = $src_w;
  274.         if ( ! $dst_h )
  275.             $dst_h = $src_h;
  276.  
  277.         $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
  278.  
  279.         if ( $src_abs ) {
  280.             $src_w -= $src_x;
  281.             $src_h -= $src_y;
  282.         }
  283.  
  284.         if ( function_exists( 'imageantialias' ) )
  285.             imageantialias( $dst, true );
  286.  
  287.         imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
  288.  
  289.         if ( is_resource( $dst ) ) {
  290.             imagedestroy( $this->image );
  291.             $this->image = $dst;
  292.             $this->update_size();
  293.             return true;
  294.         }
  295.  
  296.         return new WP_Error( 'image_crop_error', __('Image crop failed.'), $this->file );
  297.     }
  298.  
  299.     /**
  300.      * Rotates current image counter-clockwise by $angle.
  301.      * Ported from image-edit.php
  302.      *
  303.      * @since 3.5.0
  304.      *
  305.      * @param float $angle
  306.      * @return true|WP_Error
  307.      */
  308.     public function rotate( $angle ) {
  309.         if ( function_exists('imagerotate') ) {
  310.             $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
  311.             $rotated = imagerotate( $this->image, $angle, $transparency );
  312.  
  313.             if ( is_resource( $rotated ) ) {
  314.                 imagealphablending( $rotated, true );
  315.                 imagesavealpha( $rotated, true );
  316.                 imagedestroy( $this->image );
  317.                 $this->image = $rotated;
  318.                 $this->update_size();
  319.                 return true;
  320.             }
  321.         }
  322.         return new WP_Error( 'image_rotate_error', __('Image rotate failed.'), $this->file );
  323.     }
  324.  
  325.     /**
  326.      * Flips current image.
  327.      *
  328.      * @since 3.5.0
  329.      *
  330.      * @param bool $horz Flip along Horizontal Axis
  331.      * @param bool $vert Flip along Vertical Axis
  332.      * @return true|WP_Error
  333.      */
  334.     public function flip( $horz, $vert ) {
  335.         $w = $this->size['width'];
  336.         $h = $this->size['height'];
  337.         $dst = wp_imagecreatetruecolor( $w, $h );
  338.  
  339.         if ( is_resource( $dst ) ) {
  340.             $sx = $vert ? ($w - 1) : 0;
  341.             $sy = $horz ? ($h - 1) : 0;
  342.             $sw = $vert ? -$w : $w;
  343.             $sh = $horz ? -$h : $h;
  344.  
  345.             if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
  346.                 imagedestroy( $this->image );
  347.                 $this->image = $dst;
  348.                 return true;
  349.             }
  350.         }
  351.         return new WP_Error( 'image_flip_error', __('Image flip failed.'), $this->file );
  352.     }
  353.  
  354.     /**
  355.      * Saves current in-memory image to file.
  356.      *
  357.      * @since 3.5.0
  358.      *
  359.      * @param string|null $filename
  360.      * @param string|null $mime_type
  361.      * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
  362.      */
  363.     public function save( $filename = null, $mime_type = null ) {
  364.         $saved = $this->_save( $this->image, $filename, $mime_type );
  365.  
  366.         if ( ! is_wp_error( $saved ) ) {
  367.             $this->file = $saved['path'];
  368.             $this->mime_type = $saved['mime-type'];
  369.         }
  370.  
  371.         return $saved;
  372.     }
  373.  
  374.     /**
  375.      * @param resource $image
  376.      * @param string|null $filename
  377.      * @param string|null $mime_type
  378.      * @return WP_Error|array
  379.      */
  380.     protected function _save( $image, $filename = null, $mime_type = null ) {
  381.         list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
  382.  
  383.         if ( ! $filename )
  384.             $filename = $this->generate_filename( null, null, $extension );
  385.  
  386.         if ( 'image/gif' == $mime_type ) {
  387.             if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) )
  388.                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
  389.         }
  390.         elseif ( 'image/png' == $mime_type ) {
  391.             // convert from full colors to index colors, like original PNG.
  392.             if ( function_exists('imageistruecolor') && ! imageistruecolor( $image ) )
  393.                 imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
  394.  
  395.             if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) )
  396.                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
  397.         }
  398.         elseif ( 'image/jpeg' == $mime_type ) {
  399.             if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) )
  400.                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
  401.         }
  402.         else {
  403.             return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
  404.         }
  405.  
  406.         // Set correct file permissions
  407.         $stat = stat( dirname( $filename ) );
  408.         $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
  409.         @ chmod( $filename, $perms );
  410.  
  411.         /**
  412.          * Filters the name of the saved image file.
  413.          *
  414.          * @since 2.6.0
  415.          *
  416.          * @param string $filename Name of the file.
  417.          */
  418.         return array(
  419.             'path'      => $filename,
  420.             'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
  421.             'width'     => $this->size['width'],
  422.             'height'    => $this->size['height'],
  423.             'mime-type' => $mime_type,
  424.         );
  425.     }
  426.  
  427.     /**
  428.      * Returns stream of current image.
  429.      *
  430.      * @since 3.5.0
  431.      *
  432.      * @param string $mime_type The mime type of the image.
  433.      * @return bool True on success, false on failure.
  434.      */
  435.     public function stream( $mime_type = null ) {
  436.         list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
  437.  
  438.         switch ( $mime_type ) {
  439.             case 'image/png':
  440.                 header( 'Content-Type: image/png' );
  441.                 return imagepng( $this->image );
  442.             case 'image/gif':
  443.                 header( 'Content-Type: image/gif' );
  444.                 return imagegif( $this->image );
  445.             default:
  446.                 header( 'Content-Type: image/jpeg' );
  447.                 return imagejpeg( $this->image, null, $this->get_quality() );
  448.         }
  449.     }
  450.  
  451.     /**
  452.      * Either calls editor's save function or handles file as a stream.
  453.      *
  454.      * @since 3.5.0
  455.      *
  456.      * @param string|stream $filename
  457.      * @param callable $function
  458.      * @param array $arguments
  459.      * @return bool
  460.      */
  461.     protected function make_image( $filename, $function, $arguments ) {
  462.         if ( wp_is_stream( $filename ) )
  463.             $arguments[1] = null;
  464.  
  465.         return parent::make_image( $filename, $function, $arguments );
  466.     }
  467. }
  468.