PHP 미리 보기 그림 생 성 및 그림 워 터 마크 제작

1.시작
사이트 에 사진 을 올 리 는 과정 에서 미리 보기 기능 을 자주 사용한다.여기에 나 는 미리 보기 그림 을 만 들 수 있 고 워 터 마크 그림 을 추가 할 수 있 는 이미지 류 를 직접 썼 다.
2.미리 보기 그림 생 성 방법
     미리 보기 그림 을 만 듭 니 다.크기 조정 비율 을 어떻게 계산 하 느 냐 가 관건 입 니 다.
     여기 서 저 는 그림 의 등비 크기,너비,높이 의 몇 가지 흔 한 변화 에 따라 크기 조정 비율 알고리즘 을 얻 었 습 니 다.새 그림(즉 미리 보기 그림)의 너비 와 높이 를 각각 원 그림 의 너비 로 나 누고 어느 값 이 큰 지 보고 크기 조정 비율 로 하 는 것 입 니 다.
     크기 조정 비율  = Max({새 그림 높이  / 원 도 높이,  새 그림 너비  / 원 폭})
     즉:
      If(새 그림 높이  / 원 도 높이  >  (새 그림 너비  / 원 폭  {
              크기 조정 비율=  새 그림 높이  / 원 도 높이;
      }ELSE {
             크기 조정 비율=  새 그림 너비/원 그림 너비;
     }
 필드 의 그림 크기 조정 및 처리 방법 을 보 여 줍 니 다.
 e.g
장면 1,원본 그림 이 새 그림 보다 큰 경우,크기 조정 비율=  새 그림 너비/원본 그림 너비:

장면 2,원본 그림 이 새 그림 보다 큰 경우 b.크기 조정 비율=  새 그림 높이/원본 그림 높이:

장면 3.원 도 는 새 그림 보다 큰 상황 이 고 새 그림 의 너비 와 높이 가 같다.즉,새 그림 의 모양 이 정사각형 이면 위의 크기 조정 알고리즘 도 적용 된다.
장면 4,만약"새 그림 너비>=원 그림 너비"  ,동시에  “새 그림 높이>=원 그림 높이"는 그림 을 크기 조정 하지 않 고 확대 하지 않 고 원 그림 을 유지 합 니 다.

장면 5,만약"새 그림 너비<원 그림 너비",동시에  “새 그림 높이>=원 그림 높이"  ,그러면 설정 을 먼저 할 게 요.  “새 그림 의 높이=원 그림 의 높이"를 다시 자 릅 니 다.

장면 6,"새로운 그림 높이<원 그림 높이",동시에  “새 그림 너비>=원 그림 너비"  ,그러면 설정 을 먼저 할 게 요.  “새 그림 너비=원 그림 너비"를 다시 자 릅 니 다.

3.워 터 마크 사진 을 추가 하 는 방법
   워 터 마크 를 추가 하 는 것 은 매우 쉽다.나 는 여기 서 그렇게 복잡 한 것 을 고려 하지 않 았 는데 주로 워 터 마크 의 위치 가 그림 의 오른쪽 아래 에 있 고 워 터 마크 가 그림 에 있 는 크기 를 조절 하 는 것 이다.예 를 들 어 목표 그림 이 워 터 마크 그림 의 크기 와 비슷 할 때 먼저 워 터 마크 그림 을 크기 조정 한 다음 에 워 터 마크 그림 을 추가 해 야 합 니 다.

왼쪽 두 폭 의 그림,위 에는 원 그림,아래 는 워 터 마크 그림,오른쪽 크기 조정 후 워 터 마크 를 넣 은 새 그림 입 니 다.
 4.도표

5.PHP 코드
5.1.구조 함수construct()
     Image 클래스 에 서 는 구조 함수 를 제외 합 니 다.construct()는 Public 이 고 다른 함 수 는 private 입 니 다.즉 함수construct()에 서 는 미리 보기 그림 을 만 들 고 워 터 마크 를 추가 하 는 기능 을 직접 완성 하 였 습 니 다.워 터 마크 를 추가 하지 않 고 미리 보기 그림 만 생 성 한다 면 바로construct()의 인자$markPath 를 null 로 설정 하면 됩 니 다.
     그 중,"$this->quality=$quality?$quality : 75;” JPG 그림 으로 출력 을 제어 할 때 그림 품질(0-100)을 제어 하고 기본 값 은 75 입 니 다.

  /**
   * 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();
  }

 참고:선생님 은 미리 보기 그림 을 만 들 고 새 그림 에 워 터 마크 그림 을 추가 합 니 다. 
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);
  }

워 터 마크 사진 추가 중 하 나 를 사용 합 니 다thumb 1()함수 로 워 터 마크 그림 크기 조정:

  /**
   *    (    )
   * @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['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();
 }

 /**
  *    
  */
 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('         .' . $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 애니메이션 의 크기 를 조정 할 수 없다 는 단점 이 있 습 니 다.프레임 처리 와 관련 되 어 번 거 롭 기 때 문 입 니 다.
 이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기