PHP upload pictures, automatically cropped to thumbnails, wide unlimited height

Source: Internet
Author: User
Tags php tutorial save file scale image trim

PHP Tutorial upload pictures, automatically cropped into thumbnails, wide unlimited height

<?php
$Id: image.php 1937 2009-01-05 19:09:40z Dualface $

/**
* Define Helper_image class and Helper_imagegd class
*
* @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
*/

/**
* Helper_image class encapsulates an image-oriented operation
*
* Developers cannot directly construct instances of the class, but should use Helper_image::createfromfile ()
* Static method creates an instance of the Image class.
*
* When working with large pictures, make sure that PHP can allocate enough memory.
*
* @author Yulei Liao <liaoyulei@qeeyuan.com>
* @version $Id: image.php 1937 2009-01-05 19:09:40z Dualface $
* @package Helper
*/
Abstract class Helper_image
{
/**
* Create Helper_imagegd object from specified file
*
Usage
* @code PHP
* $image = helper_image::createfromfile (' 1.jpg ');
* $image->resize ($width, $height);
* $image->saveasjpeg (' 2.jpg ');
* @endcode
*
* For uploaded files, the extension is not included in the temporary file name.
* Therefore, you need to create an Image object in the following ways:
*
* @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 Specify extension
*
* @return HELPER_IMAGEGD The Helper_imagegd object created from the file
* @throw q_notimplementedexception
*/
static function CreateFromFile ($filename, $fileext)
{
$fileext = Trim (Strtolower ($fileext), '. ');
$ext 2functions = Array (
' jpg ' => ' imagecreatefromjpeg ',
' JPEG ' => ' imagecreatefromjpeg ',
' PNG ' => ' imagecreatefrompng ',
' gif ' => ' imagecreatefromgif '
);

if (!isset ($ext 2functions[$fileext]))
{
throw new Q_notimplementedexception (' Imagecreateform '. $fileext));
}

$handle = Call_user_func ($ext 2functions[$fileext], $filename);
return new HELPER_IMAGEGD ($handle);
}

/**
* Converts a 16-color value to an 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 default color returned when invalid color values are used
*
* @return Array consists of RGB three-color arrays
*/
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 >>) & 0xFF, ($dec >> 8) & 0xFF, $dec & 0xff);
}
}

/**
* The Helper_imagegd class encapsulates a GD handle that is used to manipulate the image
*
* @author Yulei Liao <liaoyulei@qeeyuan.com>
* @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 ();
}

/**
* Fast scale image to specified size (poor quality)
*
* @param int $width the new width
* @param int $height a new height
*
* @return Helper_imagegd Returns the Helper_imagegd object itself to achieve 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;
}

/**
* Zoom image to specified size (good quality, slower than resize ())
*
* @param int $width the new width
* @param int $height a new height
*
* @return Helper_imagegd Returns the Helper_imagegd object itself to achieve 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, but do not zoom operation
*
Usage
* @code PHP
* $image->resizecanvas ($width, $height, ' top-left ');
* @endcode
*
* $pos parameter specifies where the image content is aligned when resizing the image.
* The available values for the $pos parameters are:
*
*-Left: aligned
*-Right: right-aligned
*-Center: Centre alignment
*-top: Snap to Tops
*-bottom: Bottom alignment
*-Top-left, left-top: Align Top left corner
*-Top-right, right-top: Align Top right corner
*-Bottom-left, left-bottom: Align bottom left corner
*-Bottom-right, right-bottom: Align Bottom right corner
*
* If an invalid $pos parameter is specified, it is equivalent to the specified center.
*
* @param int $width a new height
* @param int $height the new width
* @param string $pos Adjust the change of image position
* @param string $bgcolor The default color for blank parts
*
* @return Helper_imagegd Returns the Helper_imagegd object itself to achieve 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 picture based on the Pos property
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;
}

/**
* Cut the image to a specified size while maintaining the image aspect ratio
*
* Crop () when scaling an image, you can maintain the aspect ratio of the image, thus ensuring that the image does not pull high or flatten.
*
* Crop () By default, the maximum scaling is calculated according to the $width and $height parameters.
* Keep the cut image to the fullest extent possible to fill the picture.
*
* For example, the size of the source diagram is x 600, and the specified $width and $height are 200 and 100.
* Then the source diagram is first reduced to 150 x, and then the extra 50 pixel height is cut off.
*
Usage
* @code PHP
* $image->crop ($width, $height);
* @endcode
*
* If you want the final build picture to always contain the full image content, you should specify $options parameters.
* The available values for this parameter are:
*
*-Fullimage: Whether to keep the full image
*-POS: Alignment when scaling
*-bgcolor: background color of extra parts when scaling
*-Enlarge: whether to allow amplification
*-Reduce: whether to allow narrowing
*
* The available values for the $options [' POS '] parameter are:
*
*-Left: aligned
*-Right: right-aligned
*-Center: Centre alignment
*-top: Snap to Tops
*-bottom: Bottom alignment
*-Top-left, left-top: Align Top left corner
*-Top-right, right-top: Align Top right corner
*-Bottom-left, left-bottom: Align bottom left corner
*-Bottom-right, right-bottom: Align Bottom right corner
*
* If an invalid $pos parameter is specified, it is equivalent to the specified center.
*
* Each option in the $options can be specified individually, such as placing the image in the lower-right corner of the new picture when the cut is allowed.
*
* @code PHP
* $image->crop ($width, $height, Array (' pos ' => ' Right-bottom '));
* @endcode
*
* @param int $width the new width
* @param int $height a new height
* @param array $options cut options
*
* @return Helper_imagegd Returns the Helper_imagegd object itself to achieve 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);

       //calculation of aspect ratio based on source graph
        $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, select the minimum 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;

Calculates the width, position, and height of the target area
$DST _w = $full _w * $ratio;
$DST _h = $full _h * $ratio;

Depending on the POS attribute to determine how to locate
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
     *
  & nbsp;  * @param string $filename Save the file name
     * @param int $quality quality parameters, default to
&NBSP;&NBSP ;   *
     * @return Helper_imagegd Returns the Helper_imagegd object itself, implementing a coherent interface
  & nbsp;  */
    function Saveasjpeg ($filename, $quality =)
    {
 & nbsp;      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 to achieve a coherent interface
*/
function Destroy ()
{
if (! $this->_handle)
{
@imagedestroy ($this->_handle);
}
$this->_handle = null;
return $this;
}
}

Call method

<?php
$image = helper_image::createfromfile (' c:a.jpg ', ' jpg ');
$image->resampled; // Zoom to 100px * 100PX
$image->saveasjpeg (' c:a_output.jpg ', MB);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.