PHP thumbnail generation and image watermark making detailed

Source: Internet
Author: User
Tags watermark images
This article is mainly for you to introduce the PHP thumbnail generation and image watermark production process, PHP to achieve watermark addition and thumbnail generation of related steps, with a certain reference value, interested in small partners can refer to

1. Start

In the website upload picture process, often use the thumbnail function. Here I wrote a picture of the image class, can generate thumbnails, and can add a watermark map.

2. How to create a thumbnail image

The key to generating thumbnails is how to calculate the zoom ratio.

Here, I based on the picture, such as zoom, width and height of several common changes, the calculation of a scaling ratio algorithm is to use the new map (that is, thumbnails) of the width of the height, divided by the width of the original image, to see which value is large, take it as a zoom ratio:

Zoom ratio = Max ({New figure height/original height, new figure width/original width})

That is

If (New figure height/original height) > (New figure width/original width) {

Zoom ratio = new figure height/original height;

}else {

Zoom ratio = new figure width/original width;

}

Here is a list of picture scaling scenarios for the scene, and how to handle them:

e.g

Scenario 1, when the original image is larger than the new figure, the zoom ratio = new Width/original width:

Scenario 2, where the original image is larger than the new figure, B. zoom ratio = new figure height/original height:

Scenario 3, the original picture is larger than the new figure, and the new image width is equal, that is, the new shape is a square, then the above scaling algorithm is also applicable.

Scenario 4, if "New figure width >= original width", and "new figure height >= original height", then do not scale the picture, nor enlarge the picture, keep the original image.

Scene 5, if "New figure width < original width", and "new figure height >= original height", then set "new figure height = original height", and then cut.

Scene 6, if "New figure height < original height", and "new figure width >= original width", then set "new figure width = original width", and then cut.

3. How to add a watermark image
Watermark is easy to add, I don't consider it so complicated here, mainly control the watermark position in the lower right corner of the picture, and control the size of the watermark in the picture. For example, when the target image and watermark map size Close, then you need to wait for the water to print pictures, and then add a watermark image.

Two pictures on the left, above is the original, the following is the watermark, the right side of the scale after the new image watermark.

4. Class Diagram


5.PHP Code

5.1. Constructor __construct ()

In the image class, except that the constructor __construct () is public, the other functions are private. That is, in the function __construct (), the ability to generate thumbnails and add watermarks is done directly. If you only generate thumbnails and do not need to add watermarks, then directly in the __construct () parameter $markpath, set to null.

Where, "$this->quality = $quality?" $quality: 75; "Control the image quality when the output is JPG (0-100), the default value is 75;

  /** * Image constructor. * @param string $imagePath picture path * @param string $markPath watermark picture path * @param int $new _width thumbnail width * @param int $new _hei ght thumbnail height * @param int $quality jpg picture grid output quality */Public function __construct (string $imagePath, String $m  Arkpath = null, int $new _width = null, int $new _height = null, int $quality =    {$this->imgpath = $_server[' Document_root '). $imagePath;    $this->watermarkpath = $markPath; $this->newwidth = $new _width?    $new _width: $this->width; $this->newheight = $new _height?    $new _height: $this->height; $this->quality = $quality?    $quality: 75;    List ($this->width, $this->height, $this->type) = getimagesize ($this->imgpath);    $this->img = $this->_loadimg ($this->imgpath, $this->type);    Generate thumbnails $this->_thumb ();    Add watermark Picture if (!empty ($this->watermarkpath)) $this->_addwatermark (); Output Picture $this->_Outputimg (); }

Note: As a thumbnail, add a watermark image to the new image.

5.2. Generate thumbnail function _thumb ()

   /** * thumbnails (scaled according to the width and height of the setting) */Private Function _thumb () {//If the original image itself is smaller than the thumbnail, the original height if ($this->newwidth &G T    $this->width) $this->newwidth = $this->width;    if ($this->newheight > $this->height) $this->newheight = $this->height;    Background graph length High $gd _width = $this->newwidth;    $GD _height = $this->newheight; If the thumbnail width is high, and one side equals the width of the original, the IF ($gd _width = = $this->width | | $gd _height = = $this->height) {$this-&GT;NEWWI      DTH = $this->width;    $this->newheight = $this->height;      } else {//calculate zoom ratio $per = 1; if (($this->newheight/$this->height) > ($this->newwidth/$this->width) {$per = $this->newhei      ght/$this->height;      } else {$per = $this->newwidth/$this->width;        } if ($per < 1) {$this->newwidth = $this->width * $per;      $this->newheight = $this->height * $per; }} $this->newimg = $this->_createimg ($gd _width, $gd _height, $this->type); Imagecopyresampled ($this->newimg, $this->img, 0, 0, 0, 0, $this->newwidth, $this->newheight, $this-  width, $this->height); }

The Generate thumbnail function, _thumb (), is encoded according to the previous analysis.

5.3. Add Watermark Image function _addwatermark ()

   /**   * Add watermark */  Private Function _addwatermark ()  {    $ratio = 1/5;//watermark scaling ratio    $Width = Imagesx ($ THIS->NEWIMG);    $Height = Imagesy ($this->newimg);    $n _width = $Width * $ratio;    $n _height = $Width * $ratio;    List ($markWidth, $markHeight, $markType) = getimagesize ($this->watermarkpath);    if ($n _width > $markWidth) $n _width = $markWidth;    if ($n _height > $markHeight) $n _height = $markHeight;    $IMG = $this->_loadimg ($this->watermarkpath, $markType);    $IMG = $this->_thumb1 ($Img, $markWidth, $markHeight, $markType, $n _width, $n _height);    $markWidth = Imagesx ($IMG);    $markHeight = Imagesy ($IMG);    Imagecopyresampled ($this->newimg, $IMG, $Width-$markWidth -10, $Height-$markHeight -10, 0, 0, $markWidth, $markHe ight, $markWidth, $markHeight);    Imagedestroy ($IMG);  }

In the Add watermark picture, use a _thumb1 () function to indent the print image:

  /**   * Thumbnail (proportional)   * @param resource $img image stream   * @param int $width   * @param int $height   * @param int $type   * @param int $new _width   * @param int $new _height   * @return Resource   *  /Private Function _THUMB1 ($ IMG, $width, $height, $type, $new _width, $new _height)  {    if ($width < $height) {      $new _width = ($new _heig ht/$height) * $width;    } else {      $new _height = ($new _width/$width) * $height;    }    $NEWIMG = $this->_createimg ($new _width, $new _height, $type);    Imagecopyresampled ($NEWIMG, $img, 0, 0, 0, 0, $new _width, $new _height, $width, $height);    return $newImg;  }

5.4. Complete code:

<?php/** * image processing, generate thumbnails and add watermark images * Created by Phpstorm.  * User:andy * date:17-1-3 * time: Morning 11:55 */class image{//original private $imgPath;//Picture address private $width; Image width Private $height;  Picture height private $type;  Picture type private $img; Picture (Image stream)//thumbnail private $newImg; Thumbnail (image stream) private $newWidth; Private $newHeight; Watermark Path Private $waterMarkPath; Output image quality, jpg valid private $quality;  /** * Image constructor.  * @param string $imagePath picture path * @param string $markPath watermark picture path * @param int $new _width thumbnail width * @param int $new _height Thumbnail height * @param int $quality jpg picture grid output quality */Public function __construct (string $imagePath, string $markPath = null , int $new _width = null, int $new = null, int $quality = _height) {$this->imgpath = $_server[' Document_root '].  $imagePath;  $this->watermarkpath = $markPath; $this->newwidth = $new _width?  $new _width: $this->width; $this->newheight = $new _height?  $new _height: $this->height; $this->quality = $qualiTy?  $quality: 75;  List ($this->width, $this->height, $this->type) = getimagesize ($this->imgpath);  $this->img = $this->_loadimg ($this->imgpath, $this->type);  Generate thumbnails $this->_thumb ();  Add watermark Picture if (!empty ($this->watermarkpath)) $this->_addwatermark (); Output picture $this->_outputimg ();  }/** * Image output */Private Function _outputimg () {switch ($this->type) {Case 1://GIF Imagegif ($this->newimg,    $this->imgpath);   Break    Case 2://JPG if (intval ($this->quality) < 0 | | intval ($this->quality) > $this->quality = 75;    Imagejpeg ($this->newimg, $this->imgpath, $this->quality);   Break    Case 3://PNG Imagepng ($this->newimg, $this->imgpath);  Break  } Imagedestroy ($this->newimg); Imagedestroy ($this->img);  }/** * Add watermark */Private Function _addwatermark () {$ratio = 1/5;//watermark scaling ratio $Width = Imagesx ($this->newimg);  $Height = Imagesy ($this->newimg); $n _width = $Width * $ratio;  $n _height = $Width * $ratio;  List ($markWidth, $markHeight, $markType) = getimagesize ($this->watermarkpath);  if ($n _width > $markWidth) $n _width = $markWidth;  if ($n _height > $markHeight) $n _height = $markHeight;  $IMG = $this->_loadimg ($this->watermarkpath, $markType);  $IMG = $this->_thumb1 ($Img, $markWidth, $markHeight, $markType, $n _width, $n _height);  $markWidth = Imagesx ($IMG);  $markHeight = Imagesy ($IMG); Imagecopyresampled ($this->newimg, $IMG, $Width-$markWidth -10, $Height-$markHeight -10, 0, 0, $markWidth, $markHe  ight, $markWidth, $markHeight); Imagedestroy ($IMG); }/** * Thumbnails (scaled according to the width and height of the setting) */Private Function _thumb () {//If the original image itself is smaller than the thumbnail, the original height if ($this->newwidth > $this-  >width) $this->newwidth = $this->width;  if ($this->newheight > $this->height) $this->newheight = $this->height;  Background graph length High $gd _width = $this->newwidth;  $GD _height = $this->newheight; If the thumbnail width is high, and one side equals the width of the original, the IF ($gd _width = = $This->width | |   $GD _height = = $this->height) {$this->newwidth = $this->width;  $this->newheight = $this->height;   } else {//calculate zoom ratio $per = 1; if (($this->newheight/$this->height) > ($this->newwidth/$this->width) {$per = $this->newheight   /$this->height;   } else {$per = $this->newwidth/$this->width;    } if ($per < 1) {$this->newwidth = $this->width * $per;   $this->newheight = $this->height * $per;  }} $this->newimg = $this->_createimg ($gd _width, $gd _height, $this->type); Imagecopyresampled ($this->newimg, $this->img, 0, 0, 0, 0, $this->newwidth, $this->newheight, $this- width, $this->height); }/** * Thumbnail (proportional) * @param resource $img image stream * @param int $width * @param int $height * @param int $type * @param in T $new _width * @param int $new _height * @return Resource */Private Function _THUMB1 ($img, $width, $height, $type, $new _width, $new _height) {if ($widtH < $height) {$new _width = ($new _height/$height) * $width;  } else {$new _height = ($new _width/$width) * $height;  } $NEWIMG = $this->_createimg ($new _width, $new _height, $type);  Imagecopyresampled ($NEWIMG, $img, 0, 0, 0, 0, $new _width, $new _height, $width, $height); return $NEWIMG; /** * Load Picture * @param string $imgPath * @param int $type * @return Resource */Private Function _loadimg ($imgPath, $t    ype) {switch ($type) {Case 1://GIF $img = Imagecreatefromgif ($imgPath);   Break    Case 2://JPG $img = Imagecreatefromjpeg ($imgPath);   Break    Case 3://PNG $img = Imagecreatefrompng ($imgPath);   Break    Default://other type Tool::alertback (' does not support the current picture type. '. $type);  Break } return $img; }/** * Create a background image * @param int $width * @param int $height * @param int $type * @return Resource */Private function  _createimg ($width, $height, $type) {$img = Imagecreatetruecolor ($width, $height); Switch ($type) {case 3://png ImagecolortransparenT ($img, 0);    Set the background to transparent imagealphablending ($img, false);    Imagesavealpha ($img, true);   Break    Case 4://gif imagecolortransparent ($img, 0);  Break } return $img; }}

6. Call

The invocation is very simple, after introducing the class, direct new and enter the corresponding parameters:

e.g.

New Image ($_path, MARK, 400, 200, 100);

7. Summary
This image class can generate thumbnails, do not appear black edge, add watermark map, according to the size of the picture to shrink the layout of the drainage. Of course there is a disadvantage, is not to scale GIF animation, because it involves the processing of frames, more trouble.

The above is the whole content of this article, I hope that everyone's study has helped.


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.