찾다
백엔드 개발PHP 튜토리얼PHP의 모든 기능을 갖춘 비변형 이미지 자르기 작업 클래스 및 사용법에 대한 자세한 설명

이 글은 주로 PHP의 전 기능을 갖춘 비변형 이미지 자르기 작업 클래스와 사용법을 소개하고, PHP 작업 이미지의 자르기, 크기 조정 및 기타 관련 기술을 예제 형식으로 분석합니다. 도움이 필요한 친구들은 참고할 수 있습니다

The 자세한 내용은 다음과 같습니다.

필요한 경우 기본적으로 사진 자르기나 썸네일 생성에 문제가 없으며 필요한 모든 기능이 포함되어 있으며 모두 왜곡이 없습니다.

여기에서는 4가지 모드로 나눕니다.

1. 사진을 지정된 크기로 자르고, 초과하고, 극에서 자르고, 확대/축소를 최대화하고, 충분하지 않으면 늘립니다.
2. 극중 초과 크롭해도 늘어나지 않습니다. 즉, 줄어들기만 하고 확대되지 않습니다. 크롭하면 패딩이 생성되며, 이는 png 투명도로 제거할 수 있습니다.
3. 자르지 않고 크기만 조정하고 패딩이 부족합니다.
4. 모든 사진 정보를 보관하세요. 자르지 않고 확대/축소만 하고 필요한 경우 패딩을 사용하지 않습니다. 예를 들어, 그림이 600X600이고 이제 120X100을 생성하려는 경우 크기 조정 후 실제 유효 픽셀은 100X100입니다. 100X100 사진만 생성되고 세 번째 이 모드는 120X100 크기를 생성하고 패딩이 있습니다

코드는 다음과 같습니다. (여기 코드는 이 웹사이트 http://tools.jb51의 온라인 도구를 통해 형식화되었습니다. .net/code/jb51_php_format):

<?php
/**
* Author : smallchicken
* mode 1 : 强制裁剪,生成图片严格按照需要,不足放大,超过裁剪,图片始终铺满
* mode 2 : 和1类似,但不足的时候 不放大 会产生补白,可以用png消除。
* mode 3 : 只缩放,不裁剪,保留全部图片信息,会产生补白,
* mode 4 : 只缩放,不裁剪,保留全部图片信息,生成图片大小为最终缩放后的图片有效信息的实际大小,不产生补白
* 默认补白为白色,如果要使补白成透明像素,请使用SaveAlpha()方法代替SaveImage()方法
*
* 调用方法:
*
* $ic=new ImageCrop(&#39;old.jpg&#39;,&#39;afterCrop.jpg&#39;);
* $ic->Crop(120,80,2);
* $ic->SaveImage();
*    //$ic->SaveAlpha();将补白变成透明像素保存
* $ic->destory();
*
*
*/
class ImageCrop {
  var $sImage;
  var $dImage;
  var $src_file;
  var $dst_file;
  var $src_width;
  var $src_height;
  var $src_ext;
  var $src_type;
  function ImageCrop($src_file,$dst_file=&#39;&#39;) {
    $this->src_file=$src_file;
    $this->dst_file=$dst_file;
    $this->LoadImage();
  }
  function SetSrcFile($src_file) {
    $this->src_file=$src_file;
  }
  function SetDstFile($dst_file) {
    $this->dst_file=$dst_file;
  }
  function LoadImage() {
    list($this->src_width, $this->src_height, $this->src_type) = getimagesize($this->src_file);
    switch($this->src_type) {
      case IMAGETYPE_JPEG :
      $this->sImage=imagecreatefromjpeg($this->src_file);
      $this->ext=&#39;jpg&#39;;
      break;
      case IMAGETYPE_PNG :
      $this->sImage=imagecreatefrompng($this->src_file);
      $this->ext=&#39;png&#39;;
      break;
      case IMAGETYPE_GIF :
      $this->sImage=imagecreatefromgif($this->src_file);
      $this->ext=&#39;gif&#39;;
      break;
      default:
      exit();
    }
  }
  function SaveImage($fileName=&#39;&#39;) {
    $this->dst_file=$fileName ? $fileName : $this->dst_file;
    switch($this->src_type) {
      case IMAGETYPE_JPEG :
      imagejpeg($this->dImage,$this->dst_file,100);
      break;
      case IMAGETYPE_PNG :
      imagepng($this->dImage,$this->dst_file);
      break;
      case IMAGETYPE_GIF :
      imagegif($this->dImage,$this->dst_file);
      break;
      default:
      break;
    }
  }
  function OutImage() {
    switch($this->src_type) {
      case IMAGETYPE_JPEG :
      header(&#39;Content-type: image/jpeg&#39;);
      imagejpeg($this->dImage);
      break;
      case IMAGETYPE_PNG :
      header(&#39;Content-type: image/png&#39;);
      imagepng($this->dImage);
      break;
      case IMAGETYPE_GIF :
      header(&#39;Content-type: image/gif&#39;);
      imagegif($this->dImage);
      break;
      default:
      break;
    }
  }
  function SaveAlpha($fileName=&#39;&#39;) {
    $this->dst_file=$fileName ? $fileName . &#39;.png&#39; : $this->dst_file .&#39;.png&#39;;
    imagesavealpha($this->dImage, true);
    imagepng($this->dImage,$this->dst_file);
  }
  function OutAlpha() {
    imagesavealpha($this->dImage, true);
    header(&#39;Content-type: image/png&#39;);
    imagepng($this->dImage);
  }
  function destory() {
    imagedestroy($this->sImage);
    imagedestroy($this->dImage);
  }
  function Crop($dst_width,$dst_height,$mode=1,$dst_file=&#39;&#39;) {
    if($dst_file) $this->dst_file=$dst_file;
    $this->dImage = imagecreatetruecolor($dst_width,$dst_height);
    $bg = imagecolorallocatealpha($this->dImage,255,255,255,127);
    imagefill($this->dImage, 0, 0, $bg);
    imagecolortransparent($this->dImage,$bg);
    $ratio_w=1.0 * $dst_width / $this->src_width;
    $ratio_h=1.0 * $dst_height / $this->src_height;
    $ratio=1.0;
    switch($mode) {
      case 1:    // always crop
      if( ($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
        $ratio = $ratio_w < $ratio_h ? $ratio_h : $ratio_w;
        $tmp_w = (int)($dst_width / $ratio);
        $tmp_h = (int)($dst_height / $ratio);
        $tmp_img=imagecreatetruecolor($tmp_w , $tmp_h);
        $src_x = (int) (($this->src_width-$tmp_w)/2) ;
        $src_y = (int) (($this->src_height-$tmp_h)/2) ;
        imagecopy($tmp_img, $this->sImage, 0,0,$src_x,$src_y,$tmp_w,$tmp_h);
        imagecopyresampled($this->dImage,$tmp_img,0,0,0,0,$dst_width,$dst_height,$tmp_w,$tmp_h);
        imagedestroy($tmp_img);
      } else {
        $ratio = $ratio_w < $ratio_h ? $ratio_h : $ratio_w;
        $tmp_w = (int)($this->src_width * $ratio);
        $tmp_h = (int)($this->src_height * $ratio);
        $tmp_img=imagecreatetruecolor($tmp_w ,$tmp_h);
        imagecopyresampled($tmp_img,$this->sImage,0,0,0,0,$tmp_w,$tmp_h,$this->src_width,$this->src_height);
        $src_x = (int)($tmp_w - $dst_width) / 2 ;
        $src_y = (int)($tmp_h - $dst_height) / 2 ;
        imagecopy($this->dImage, $tmp_img, 0,0,$src_x,$src_y,$dst_width,$dst_height);
        imagedestroy($tmp_img);
      }
      break;
      case 2:    // only small
      if($ratio_w < 1 && $ratio_h < 1) {
        $ratio = $ratio_w < $ratio_h ? $ratio_h : $ratio_w;
        $tmp_w = (int)($dst_width / $ratio);
        $tmp_h = (int)($dst_height / $ratio);
        $tmp_img=imagecreatetruecolor($tmp_w , $tmp_h);
        $src_x = (int) ($this->src_width-$tmp_w)/2 ;
        $src_y = (int) ($this->src_height-$tmp_h)/2 ;
        imagecopy($tmp_img, $this->sImage, 0,0,$src_x,$src_y,$tmp_w,$tmp_h);
        imagecopyresampled($this->dImage,$tmp_img,0,0,0,0,$dst_width,$dst_height,$tmp_w,$tmp_h);
        imagedestroy($tmp_img);
      } elseif($ratio_w > 1 && $ratio_h > 1) {
        $dst_x = (int) abs($dst_width - $this->src_width) / 2 ;
        $dst_y = (int) abs($dst_height -$this->src_height) / 2;
        imagecopy($this->dImage, $this->sImage,$dst_x,$dst_y,0,0,$this->src_width,$this->src_height);
      } else {
        $src_x=0;
        $dst_x=0;
        $src_y=0;
        $dst_y=0;
        if(($dst_width - $this->src_width) < 0) {
          $src_x = (int) ($this->src_width - $dst_width)/2;
          $dst_x =0;
        } else {
          $src_x =0;
          $dst_x = (int) ($dst_width - $this->src_width)/2;
        }
        if( ($dst_height -$this->src_height) < 0) {
          $src_y = (int) ($this->src_height - $dst_height)/2;
          $dst_y = 0;
        } else {
          $src_y = 0;
          $dst_y = (int) ($dst_height - $this->src_height)/2;
        }
        imagecopy($this->dImage, $this->sImage,$dst_x,$dst_y,$src_x,$src_y,$this->src_width,$this->src_height);
      }
      break;
      case 3:    // keep all image size and create need size
      if($ratio_w > 1 && $ratio_h > 1) {
        $dst_x = (int)(abs($dst_width - $this->src_width )/2) ;
        $dst_y = (int)(abs($dst_height- $this->src_height)/2) ;
        imagecopy($this->dImage, $this->sImage, $dst_x,$dst_y,0,0,$this->src_width,$this->src_height);
      } else {
        $ratio = $ratio_w > $ratio_h ? $ratio_h : $ratio_w;
        $tmp_w = (int)($this->src_width * $ratio);
        $tmp_h = (int)($this->src_height * $ratio);
        $tmp_img=imagecreatetruecolor($tmp_w ,$tmp_h);
        imagecopyresampled($tmp_img,$this->sImage,0,0,0,0,$tmp_w,$tmp_h,$this->src_width,$this->src_height);
        $dst_x = (int)(abs($tmp_w -$dst_width )/2) ;
        $dst_y = (int)(abs($tmp_h -$dst_height)/2) ;
        imagecopy($this->dImage, $tmp_img, $dst_x,$dst_y,0,0,$tmp_w,$tmp_h);
        imagedestroy($tmp_img);
      }
      break;
      case 4:    // keep all image but create actually size
      if($ratio_w > 1 && $ratio_h > 1) {
        $this->dImage = imagecreatetruecolor($this->src_width,$this->src_height);
        imagecopy($this->dImage, $this->sImage,0,0,0,0,$this->src_width,$this->src_height);
      } else {
        $ratio = $ratio_w > $ratio_h ? $ratio_h : $ratio_w;
        $tmp_w = (int)($this->src_width * $ratio);
        $tmp_h = (int)($this->src_height * $ratio);
        $this->dImage = imagecreatetruecolor($tmp_w ,$tmp_h);
        imagecopyresampled($this->dImage,$this->sImage,0,0,0,0,$tmp_w,$tmp_h,$this->src_width,$this->src_height);
      }
      break;
    }
  }
  // end Crop
}
?>

위 내용은 이 글의 전체 내용이며, 모든 분들의 공부에 도움이 되길 바랍니다.


관련 추천:

PHP완전한 기능변형 이미지 자르기 작업 클래스 및 사용 예 없음

PHP+jQuery로 자동 완성 실현완전한 기능소스 코드_PHP 튜토리얼

PHP +jQuery는 자동 완성을 실현합니다전체 기능소스 코드

위 내용은 PHP의 모든 기능을 갖춘 비변형 이미지 자르기 작업 클래스 및 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
세션 고정 공격을 어떻게 방지 할 수 있습니까?세션 고정 공격을 어떻게 방지 할 수 있습니까?Apr 28, 2025 am 12:25 AM

세션 고정 공격을 방지하는 효과적인 방법은 다음과 같습니다. 1. 사용자 로그인 한 후 세션 ID 재생; 2. 보안 세션 ID 생성 알고리즘을 사용하십시오. 3. 세션 시간 초과 메커니즘을 구현하십시오. 4. HTTPS를 사용한 세션 데이터를 암호화합니다. 이러한 조치는 세션 고정 공격에 직면 할 때 응용 프로그램이 파괴 할 수 없도록 할 수 있습니다.

세션리스 인증을 어떻게 구현합니까?세션리스 인증을 어떻게 구현합니까?Apr 28, 2025 am 12:24 AM

서버 측 세션 스토리지가없는 토큰에 저장되는 토큰 기반 인증 시스템 인 JSONWEBTOKENS (JWT)를 사용하여 세션없는 인증 구현을 수행 할 수 있습니다. 1) JWT를 사용하여 토큰을 생성하고 검증하십시오. 2) HTTPS가 토큰이 가로 채지 못하도록하는 데 사용되도록, 3) 클라이언트 측의 토큰을 안전하게 저장, 4) 변조 방지를 방지하기 위해 서버 측의 토큰을 확인하기 위해 단기 접근 메커니즘 및 장기 상쾌한 토큰을 구현하십시오.

PHP 세션과 관련된 일반적인 보안 위험은 무엇입니까?PHP 세션과 관련된 일반적인 보안 위험은 무엇입니까?Apr 28, 2025 am 12:24 AM

PHP 세션의 보안 위험에는 주로 세션 납치, 세션 고정, 세션 예측 및 세션 중독이 포함됩니다. 1. HTTPS를 사용하고 쿠키를 보호하여 세션 납치를 방지 할 수 있습니다. 2. 사용자가 로그인하기 전에 세션 ID를 재생하여 세션 고정을 피할 수 있습니다. 3. 세션 예측은 세션 ID의 무작위성과 예측 불가능 성을 보장해야합니다. 4. 세션 중독 데이터를 확인하고 필터링하여 세션 중독을 방지 할 수 있습니다.

PHP 세션을 어떻게 파괴합니까?PHP 세션을 어떻게 파괴합니까?Apr 28, 2025 am 12:16 AM

PHP 세션을 파괴하려면 먼저 세션을 시작한 다음 데이터를 지우고 세션 파일을 파괴해야합니다. 1. 세션을 시작하려면 세션 _start ()를 사용하십시오. 2. Session_Unset ()을 사용하여 세션 데이터를 지우십시오. 3. 마지막으로 Session_Destroy ()를 사용하여 세션 파일을 파괴하여 데이터 보안 및 리소스 릴리스를 보장하십시오.

PHP의 기본 세션 저장 경로를 어떻게 변경할 수 있습니까?PHP의 기본 세션 저장 경로를 어떻게 변경할 수 있습니까?Apr 28, 2025 am 12:12 AM

PHP의 기본 세션 저장 경로를 변경하는 방법은 무엇입니까? 다음 단계를 통해 달성 할 수 있습니다. session_save_path를 사용하십시오 ( '/var/www/sessions'); session_start (); PHP 스크립트에서 세션 저장 경로를 설정합니다. php.ini 파일에서 세션을 설정하여 세션 저장 경로를 전 세계적으로 변경하려면 세션을 설정하십시오. memcached 또는 redis를 사용하여 ini_set ( 'session.save_handler', 'memcached')과 같은 세션 데이터를 저장합니다. ini_set (

PHP 세션에 저장된 데이터를 어떻게 수정합니까?PHP 세션에 저장된 데이터를 어떻게 수정합니까?Apr 27, 2025 am 12:23 AM

tomodifyDatainAphPessess, startSessionstession_start (), 그런 다음 $ _sessionToset, modify, orremovevariables.

PHP 세션에 배열을 저장하는 예를 제시하십시오.PHP 세션에 배열을 저장하는 예를 제시하십시오.Apr 27, 2025 am 12:20 AM

배열은 PHP 세션에 저장할 수 있습니다. 1. 세션을 시작하고 session_start ()를 사용하십시오. 2. 배열을 만들고 $ _session에 저장하십시오. 3. $ _session을 통해 배열을 검색하십시오. 4. 세션 데이터를 최적화하여 성능을 향상시킵니다.

Garbage Collection은 PHP 세션에 어떻게 효과가 있습니까?Garbage Collection은 PHP 세션에 어떻게 효과가 있습니까?Apr 27, 2025 am 12:19 AM

PHP 세션 쓰레기 수집은 만료 된 세션 데이터를 정리하기위한 확률 메커니즘을 통해 트리거됩니다. 1) 구성 파일에서 트리거 확률 및 세션 수명주기를 설정합니다. 2) CRON 작업을 사용하여 고재 응용 프로그램을 최적화 할 수 있습니다. 3) 데이터 손실을 피하기 위해 쓰레기 수집 빈도 및 성능의 균형을 맞춰야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음