Home >Backend Development >PHP Tutorial >After php uploads the image, it is automatically cropped into a thumbnail, with no limit on width and height_PHP Tutorial

After php uploads the image, it is automatically cropped into a thumbnail, with no limit on width and height_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:46:05844browse

After uploading the image in the php tutorial, it will be automatically cropped into a thumbnail, with no limit on width and height

// $Id: image.php 1937 2009-01-05 19:09:40Z dualface $

/**
* 定义 Helper_Image 类和 Helper_ImageGD 类
*
* @link http://qeephp.com/
* @copyright Copyright (c) 2006-2009 Qeeyuan Inc. {@link http://www.qeeyuan.com}
* @license New BSD License {@link http://qeephp.com/license/}
* @version $Id: image.php 1937 2009-01-05 19:09:40Z dualface $
* @package helper
*/

/**
* The Helper_Image class encapsulates operations on images
*
* Developers cannot construct instances of this class directly, but should use Helper_Image::createFromFile()
* Static method creates an instance of the Image class.
*
* When operating large images, please ensure that php can allocate enough memory.
*
* @author YuLei Liao
* @version $Id: image.php 1937 2009-01-05 19:09:40Z dualface $
* @package helper
*/
abstract class Helper_Image
{
/**
* Create a Helper_ImageGD object from the specified file
*
* Usage:
* @code php
* $image = Helper_Image::createFromFile('1.jpg');
* $image->resize($width, $height);
* $image->saveAsJpeg('2.jpg');
* @endcode
*
* For uploaded files, the temporary file name does not include the extension.
* Therefore, the following method needs to be used to create the Image object:
*
* @code php
* $ext = pathinfo($_FILES['postfile']['name'], PATHINFO_EXTENSION);
* $image = Image::createFromFile($_FILES['postfile']['tmp_name'], $ext);
* @endcode
*
* @param string $filename The full path of the image file
* @param string $fileext specifies the extension
*
* @return Helper_ImageGD Helper_ImageGD object created from file
* @throw Q_NotImplementedException
​​*/
​ static function createFromFile($filename, $fileext)
{
          $fileext = trim(strtolower($fileext), '.');
​​​​ $ext2functions = array(
             'jpg' => 'imagecreatefromjpeg',
             'jpeg' => 'imagecreatefromjpeg',
             'png' => 'imagecreatefrompng',
            'gif' => 'imagecreatefromgif'
);

if (!isset($ext2functions[$fileext]))
           {
throw new Q_NotImplementedException(__('imagecreateform' . $fileext));
}

$handle = call_user_func($ext2functions[$fileext], $filename);
          return new Helper_ImageGD($handle);
}

        /**
* Convert hexadecimal color value to rgb value
*
* Usage:
* @code php
* $color = '#369';
* list($r, $g, $b) = Helper_Image::hex2rgb($color);
* echo "red: {$r}, green: {$g}, blue: {$b}";
* @endcode
*
* @param string $color color value
* @param string $default The default color returned when invalid color values ​​are used
*
* @return array An array composed of RGB three colors
                     */
        static function hex2rgb($color, $default = 'ffffff')
        {
        $hex = trim($color, '#&Hh');
        $len = strlen($hex);
        if ($len == 3)
        {
            $hex = "{$hex[0]}{$hex[0]}{$hex[1]}{$hex[1]}{$hex[2]}{$hex[2]}";
        }
        elseif ($len < 6)
        {
            $hex = $default;
        }
        $dec = hexdec($hex);
        return array(($dec >> 16) & 0xff, ($dec >> 8) & 0xff, $dec & 0xff);
        }
}

/**
* The Helper_ImageGD class encapsulates a gd handle for operating on images
*
* @author YuLei Liao
* @version $Id: image.php 1937 2009-01-05 19:09:40Z dualface $
* @package helper
*/
class Helper_ImageGD
{
    /**
* GD resource handle
*
* @var resource
​​*/
    protected $_handle = null;

    /**
* Constructor
*
* @param resource $handle GD resource handle
​​*/
    function __construct($handle)
    {
        $this->_handle = $handle;
    }

    /**
* Destructor
​​*/
    function __destruct()
    {
            $this->destroy();
    }

    /**
* Quickly scale the image to the specified size (poor quality)
*
* @param int $width new width
* @param int $height new height
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function resize($width, $height)
    {
        if (is_null($this->_handle)) return $this;

        $dest = imagecreatetruecolor($width, $height);
        imagecopyresized($dest, $this->_handle, 0, 0, 0, 0,
            $width, $height,
            imagesx($this->_handle), imagesy($this->_handle));
        imagedestroy($this->_handle);
        $this->_handle = $dest;
        return $this;
    }

    /**
* Scale the image to the specified size (better quality, slower than resize())
*
* @param int $width new width
* @param int $height new height
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function resampled($width, $height)
    {
        if (is_null($this->_handle)) return $this;
        $dest = imagecreatetruecolor($width, $height);
        imagecopyresampled($dest, $this->_handle, 0, 0, 0, 0,
            $width, $height,
            imagesx($this->_handle), imagesy($this->_handle));
        imagedestroy($this->_handle);
        $this->_handle = $dest;
        return $this;
    }

    /**
* Resize the image without zooming
*
* Usage:
* @code php
* $image->resizeCanvas($width, $height, 'top-left');
* @endcode
*
* The $pos parameter specifies the position at which the image content is aligned when the image is resized.
* The available values ​​for the $pos parameter are:
*
* - left: left aligned
* - right: Align right
* - center: center alignment
* - top: top alignment
* - bottom: Bottom alignment
* - top-left, left-top: Align upper left corner
* - top-right, right-top: Align the upper right corner
* - bottom-left, left-bottom: Align the lower left corner
* - bottom-right, right-bottom: Align the lower right corner
*
* If an invalid $pos parameter is specified, it is equivalent to specifying center.
*
* @param int $width new height
* @param int $height new width
* @param string $pos The change in image position during adjustment
* @param string $bgcolor The default color of the blank part
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function resizeCanvas($width, $height, $pos = 'center', $bgcolor = '0xffffff')
    {
        if (is_null($this->_handle)) return $this;

        $dest = imagecreatetruecolor($width, $height);
        $sx = imagesx($this->_handle);
        $sy = imagesy($this->_handle);

// Determine how to position the original image based on the pos attribute
switch (strtolower($pos))
           {
case 'left':
              $ox = 0;
               $oy = ($height - $sy) / 2;
             break;
case 'right':
               $ox = $width - $sx;
               $oy = ($height - $sy) / 2;
             break;
case 'top':
               $ox = ($width - $sx) / 2;
              $oy = 0;
             break;
case 'bottom':
               $ox = ($width - $sx) / 2;
               $oy = $height - $sy;
             break;
case 'top-left':
case 'left-top':
               $ox = $oy = 0;
             break;
case 'top-right':
case 'right-top':
               $ox = $width - $sx;
               $oy = 0;
             break;
case 'bottom-left':
case 'left-bottom':
              $ox = 0;
               $oy = $height - $sy;
             break;
case 'bottom-right':
case 'right-bottom':
               $ox = $width - $sx;
               $oy = $height - $sy;
             break;
           default:
              $ox = ($width - $sx) / 2;
               $oy = ($height - $sy) / 2;
}

list ($r, $g, $b) = Helper_Image::hex2rgb($bgcolor, '0xffffff');
          $bgcolor = imagecolorallocate($dest, $r, $g, $b);
imagefilledrectangle($dest, 0, 0, $width, $height, $bgcolor);
Imagecolordeallocate($dest, $bgcolor);

imagecopy($dest, $this->_handle, $ox, $oy, 0, 0, $sx, $sy);
         imagedestroy($this->_handle);
           $this->_handle = $dest;

return $this;
}

    /**
* Crop the image to the specified size while maintaining the image aspect ratio
*
* crop() can maintain the aspect ratio of the image when scaling the image, thereby ensuring that the image will not be stretched or squashed.
*
* * crop() will calculate the maximum scaling ratio according to the $width and $height parameters by default,
* Keep the cropped image to fill the picture to the greatest extent.
*
* For example, the size of the source image is 800 x 600, and the specified $width and $height are 200 and 100.
* * Then the source image will first be reduced to 200 x 150 size, and then the excess 50 pixel height will be cropped.
*
* Usage:
* @code php
* $image->crop($width, $height);
* @endcode
*
* If you want the final generated image to always contain the complete image content, you should specify the $options parameter.
* * Available values ​​for this parameter are:
*
* - fullimage: Whether to keep the full image
* - pos: Alignment when zooming
* - bgcolor: The background color of the excess part when scaling
* - enlarge: Whether to allow enlargement
* - reduce: whether to allow reduction
*
* * Among them, the available values ​​​​of the $options['pos'] parameter are:
*
* - left: left aligned
* - right: Align right
* - center: center alignment
* - top: top alignment
* - bottom: Bottom alignment
* - top-left, left-top: Align upper left corner
* - top-right, right-top: Align the upper right corner
* - bottom-left, left-bottom: Align the lower left corner
* - bottom-right, right-bottom: Align the lower right corner
*
* If an invalid $pos parameter is specified, it is equivalent to specifying center.
*
* Each option in $options can be specified individually, such as placing the image in the lower right corner of the new image while allowing cropping.
*
* @code php
* $image->crop($width, $height, array('pos' => 'right-bottom'));
* @endcode
*
* @param int $width new width
* @param int $height new height
* @param array $options Cutting options
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function crop($width, $height, $options = array())
    {
        if (is_null($this->_handle)) return $this;

        $default_options = array(
            'fullimage' => false,
            'pos'       => 'center',
            'bgcolor'   => '0xfff',
            'enlarge'   => false,
            'reduce'    => true,
        );
        $options = array_merge($default_options, $options);

// Create target image
         $dest = imagecreatetruecolor($width, $height);
// Fill background color
list ($r, $g, $b) = Helper_Image::hex2rgb($options['bgcolor'], '0xffffff');
          $bgcolor = imagecolorallocate($dest, $r, $g, $b);
imagefilledrectangle($dest, 0, 0, $width, $height, $bgcolor);
Imagecolordeallocate($dest, $bgcolor);

// Calculate the aspect ratio based on the source image
$full_w = imagesx($this->_handle);
$full_h = imagesy($this->_handle);
         $ratio_w = doubleval($width) / doubleval($full_w);
         $ratio_h = doubleval($height) / doubleval($full_h);

if ($options['fullimage'])
           {
// If you want to keep the full image, choose the smallest ratio
$ratio = $ratio_w < $ratio_h ? $ratio_w : $ratio_h;
}
        else
           {
// Otherwise, choose the maximum ratio
$ratio = $ratio_w > $ratio_h ? $ratio_w : $ratio_h;
}

if (!$options['enlarge'] && $ratio > 1) $ratio = 1;
If (!$options['reduce'] && $ratio < 1) $ratio = 1;

// Calculate the width, height and position of the target area
          $dst_w = $full_w * $ratio;
          $dst_h = $full_h * $ratio;

        // 根据 pos 属性来决定如何定位
        switch (strtolower($options['pos']))
        {
        case 'left':
            $dst_x = 0;
            $dst_y = ($height - $dst_h) / 2;
            break;
        case 'right':
            $dst_x = $width - $dst_w;
            $dst_y = ($height - $dst_h) / 2;
            break;
        case 'top':
            $dst_x = ($width - $dst_w) / 2;
            $dst_y = 0;
            break;
        case 'bottom':
            $dst_x = ($width - $dst_w) / 2;
            $dst_y = $height - $dst_h;
            break;
        case 'top-left':
        case 'left-top':
            $dst_x = $dst_y = 0;
            break;
        case 'top-right':
        case 'right-top':
            $dst_x = $width - $dst_w;
            $dst_y = 0;
            break;
        case 'bottom-left':
        case 'left-bottom':
            $dst_x = 0;
            $dst_y = $height - $dst_h;
            break;
        case 'bottom-right':
        case 'right-bottom':
            $dst_x = $width - $dst_w;
            $dst_y = $height - $dst_h;
            break;
        case 'center':
        default:
            $dst_x = ($width - $dst_w) / 2;
            $dst_y = ($height - $dst_h) / 2;
        }

        imagecopyresampled($dest,  $this->_handle, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $full_w, $full_h);
        imagedestroy($this->_handle);
        $this->_handle = $dest;

        return $this;
    }

    /**
* Save as JPEG file
*
* @param string $filename Save file name
* @param int $quality quality parameter, default is 80
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function saveAsJpeg($filename, $quality = 80)
    {
        imagejpeg($this->_handle, $filename, $quality);
    }

    /**
* Save as PNG file
*
* @param string $filename Save file name
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function saveAsPng($filename)
    {
        imagepng($this->_handle, $filename);
    }

    /**
* Save as GIF file
*
* @param string $filename Save file name
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function saveAsGif($filename)
    {
        imagegif($this->_handle, $filename);
    }

    /**
* Destroy the image in memory
*
* @return Helper_ImageGD Returns the Helper_ImageGD object itself, implementing a coherent interface
​​*/
    function destroy()
    {
            if (!$this->_handle)
            {
            @imagedestroy($this->_handle);
            }
        $this->_handle = null;
        return $this;
    }
}

调用方法

$image = Helper_Image::createFromFile('c:a.jpg','jpg');
$image->resampled(100, 100);  //缩放到100px * 100PX
$image->saveAsJpeg('c:a_output.jpg', 100);

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/632971.htmlTechArticlephp教程上传图片后,自动裁剪成缩略图,宽不限高 ?php // $Id: image.php 1937 2009-01-05 19:09:40Z dualface $ /** * 定义 Helper_Image 类和 Helper_ImageGD 类 *...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn