>  기사  >  백엔드 개발  >  PHP 썸네일 생성 및 이미지 워터마크 생성에 대한 자세한 설명

PHP 썸네일 생성 및 이미지 워터마크 생성에 대한 자세한 설명

墨辰丷
墨辰丷원래의
2018-05-26 16:34:211682검색

이 글에서는 주로 PHP 썸네일 생성 및 사진 워터마크 생성 과정을 자세히 소개합니다. 워터마크 추가 및 썸네일 생성을 구현하는 PHP의 관련 단계는 특정 참고 가치가 있습니다.

1. 업로드 프로세스를 시작하세요. 웹사이트의 사진은 썸네일 기능을 자주 사용합니다. 여기에서는 썸네일을 생성하고 워터마크를 추가할 수 있는 이미지 처리를 위한 Image 클래스를 작성했습니다.

2. 썸네일 생성 방법

썸네일 생성의 핵심은 줌 비율을 계산하는 방법입니다.
여기서는 이미지 크기 조정과 너비 및 높이의 몇 가지 일반적인 변경 사항을 기반으로 크기 조정 비율을 계산하는 알고리즘을 생각해 냈습니다. 새 이미지(예: 썸네일)의 너비와 높이를 너비와 높이로 나눕니다. 원본 이미지의 높이 어떤 값이 큰지 확인하세요. 확대/축소 비율로 사용하세요.

확대/축소 비율 = 최대({새 지도 높이/원본 높이, 새 지도 너비/원본 사진 너비})

(새 그림 높이 수준(새 그래프 높이 수준/원본 그림 높이) & gt; (새 지도 너비/원본 그림 너비)) {

확대/축소 비율 = 새 지도 높이/원본 높이/원본 이미지 너비

;

}

다음은 장면의 이미지 크기 조정 시나리오 및 처리 방법입니다.

예:

Scene 1, 원본 이미지가 새 이미지보다 큰 경우 크기 조정 비율 = 새 이미지 너비/원본 이미지 너비:

시나리오 2, 원본 이미지가 새 이미지보다 큽니다. b. 크기 조정 비율 = 새 이미지 높이/원본 이미지 높이:

시나리오 3, 원본 이미지가 새 이미지보다 큽니다. 상황이고 새 이미지의 너비와 높이가 동일합니다. 즉, 새 이미지의 모양이 정사각형인 경우 위의 크기 조정 알고리즘도 적용 가능합니다.

시나리오 4, "새 이미지 너비 >= 원본 이미지 너비" 및 "새 이미지 높이 >= 원본 이미지 높이"인 경우 이미지의 크기가 조정되거나 확대되지 않고 원본 이미지가 유지됩니다.

시나리오 5, "새 이미지 너비 ad22432f9115a77a0a81ae884a8b7767= 원본 이미지 너비"인 경우 "새 이미지 너비 = 원본 이미지 너비"를 먼저 설정한 다음 잘라냅니다.

3. 사진에 워터마크를 추가하는 방법

여기서는 워터마크를 추가하는 것이 매우 쉽습니다. 여기서 가장 중요한 것은 오른쪽 하단에 있는 워터마크의 위치를 ​​제어하는 ​​것입니다. 사진의 크기와 사진의 워터마크 크기. 예를 들어, 대상 이미지와 워터마크 이미지의 크기가 가까울 경우 먼저 워터마크 이미지의 크기를 비례적으로 조정한 후 워터마크 이미지를 추가해야 합니다.

왼쪽 두 사진이 위쪽이 원본 사진, 아래쪽이 워터마크가 적용된 사진, 오른쪽이 스케일링 및 워터마크 추가 후 새 사진입니다.

4. 클래스 다이어그램

5.PHP 코드

5.1 생성자 __construct()

생성자 외에 __construct( )은 공개입니다 , 다른 기능은 비공개입니다. 즉, __construct() 함수에서 썸네일 생성 및 워터마크 추가 기능이 직접 완료됩니다. 워터마크를 추가하지 않고 썸네일만 생성하는 경우 __construct()의 $markPath 매개변수를 null로 직접 설정하세요.
여기서 "$this->quality = $quality ? $quality : 75;"는 출력이 JPG 이미지일 때 이미지 품질(0-100)을 제어하고 기본값은

  /**
   * Image constructor.
   * @param string $imagePath 图片路径
   * @param string $markPath 水印图片路径
   * @param int $new_width 缩略图宽度
   * @param int $new_height 缩略图高度
   * @param int $quality JPG图片格输出质量
   */
  public function __construct(string $imagePath,
                string $markPath = null,
                int $new_width = null,
                int $new_height = null,
                int $quality = 75)
  {
    $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);


    //生成缩略图
    $this->_thumb();
    //添加水印图片
    if (!empty($this->waterMarkPath)) $this->_addWaterMark();
    //输出图片
    $this->_outputImg();
  }
입니다.

 Note: 先生成缩略图,再在新图上添加水印 图片。 

5.2. 生成缩略图函数_thumb()

   /**
   * 缩略图(按等比例,根据设置的宽度和高度进行裁剪)
   */
  private function _thumb()
  {

    //如果原图本身小于缩略图,按原图长高
    if ($this->newWidth > $this->width) $this->newWidth = $this->width;
    if ($this->newHeight > $this->height) $this->newHeight = $this->height;

    //背景图长高
    $gd_width = $this->newWidth;
    $gd_height = $this->newHeight;

    //如果缩略图宽高,其中有一边等于原图的宽高,就直接裁剪
    if ($gd_width == $this->width || $gd_height == $this->height) {
      $this->newWidth = $this->width;
      $this->newHeight = $this->height;
    } else {

      //计算缩放比率
      $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);
  }

生成缩略图函数_thumb() ,是按照前面的分析来进行编码。 

5.3. 添加水印图片函数 _addWaterMark()    

   /**
   * 添加水印
   */
  private function _addWaterMark()
  {
    $ratio = 1 / 5; //水印缩放比率

    $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, $markHeight, $markWidth, $markHeight);
    imagedestroy($Img);
  }

在添加水印图片中,用到一个_thumb1()函数来缩放水印图片:

  /**
   * 缩略图(按等比例)
   * @param resource $img 图像流
   * @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_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;
  }

5.4. 完整代码:

<?php

/**
 * 图片处理,生成缩略图和添加水印图片
 * Created by PhpStorm.
 * User: andy
 * Date: 17-1-3
 * Time: 上午11:55
 */
class Image
{
 //原图
 private $imgPath; //图片地址
 private $width;  //图片宽度
 private $height; //图片高度
 private $type;  //图片类型
 private $img;  //图片(图像流)

 //缩略图
 private $newImg; //缩略图(图像流)
 private $newWidth;
 private $newHeight;

 //水印图路径
 private $waterMarkPath;

 //输出图像质量,jpg有效
 private $quality;

 /**
  * Image constructor.
  * @param string $imagePath 图片路径
  * @param string $markPath 水印图片路径
  * @param int $new_width 缩略图宽度
  * @param int $new_height 缩略图高度
  * @param int $quality JPG图片格输出质量
  */
 public function __construct(string $imagePath,
        string $markPath = null,
        int $new_width = null,
        int $new_height = null,
        int $quality = 75)
 {
  $this->imgPath = $_SERVER[&#39;DOCUMENT_ROOT&#39;] . $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);


  //生成缩略图
  $this->_thumb();
  //添加水印图片
  if (!empty($this->waterMarkPath)) $this->_addWaterMark();
  //输出图片
  $this->_outputImg();
 }

 /**
  *图片输出
  */
 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) > 100) $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);
 }

 /**
  * 添加水印
  */
 private function _addWaterMark()
 {
  $ratio = 1 / 5; //水印缩放比率

  $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, $markHeight, $markWidth, $markHeight);
  imagedestroy($Img);
 }

 /**
  * 缩略图(按等比例,根据设置的宽度和高度进行裁剪)
  */
 private function _thumb()
 {

  //如果原图本身小于缩略图,按原图长高
  if ($this->newWidth > $this->width) $this->newWidth = $this->width;
  if ($this->newHeight > $this->height) $this->newHeight = $this->height;

  //背景图长高
  $gd_width = $this->newWidth;
  $gd_height = $this->newHeight;

  //如果缩略图宽高,其中有一边等于原图的宽高,就直接裁剪
  if ($gd_width == $this->width || $gd_height == $this->height) {
   $this->newWidth = $this->width;
   $this->newHeight = $this->height;
  } else {

   //计算缩放比率
   $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);
 }


 /**
  * 缩略图(按等比例)
  * @param resource $img 图像流
  * @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_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;
 }

 /**
  * 加载图片
  * @param string $imgPath
  * @param int $type
  * @return resource
  */
 private function _loadImg($imgPath, $type)
 {
  switch ($type) {
   case 1: // GIF
    $img = imagecreatefromgif($imgPath);
    break;
   case 2: // JPG
    $img = imagecreatefromjpeg($imgPath);
    break;
   case 3: // PNG
    $img = imagecreatefrompng($imgPath);
    break;
   default: //其他类型
    Tool::alertBack(&#39;不支持当前图片类型.&#39; . $type);
    break;
  }
  return $img;
 }

 /**
  * 创建一个背景图像
  * @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); //设置背景为透明的
    imagealphablending($img, false);
    imagesavealpha($img, true);
    break;
   case 4://gif
    imagecolortransparent($img, 0);
    break;
  }

  return $img;
 }
}

6.调用

调用非常简单,在引入类后,直接new 并输入对应参数即可:

e.g.

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

7.小结
这个Image 类能够生成缩略图,不出现黑边,添加水印图,能根据图片的大小缩放水印图。当然有个缺点,就是不能缩放GIF的动画,因为涉及到帧的处理,比较麻烦。

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

PHP实现水印类,支持添加图片、文字、填充颜色区域

thinkPHP框架实现图像裁剪、缩放、加水印的方法详解

PHP实现随机生成水印图片功能的方法

위 내용은 PHP 썸네일 생성 및 이미지 워터마크 생성에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.