search
HomeBackend DevelopmentPHP Tutorialphp image processing class_PHP tutorial

php image processing class_PHP tutorial

Jul 13, 2016 pm 05:49 PM
classimagepathphpprivateLocationpicturedeal withrightmethodkind

class Image {
        private $path;
//Construction method is used to initialize the location of the picture
function __construct($path="./"){
                 $this->path=rtrim($path, "/")."/";
         } 
/* A shrinking of the picture
*
* Parameter $name: is the name of the image that needs to be processed
* Parameter $width: is the width after scaling
* Parameter $height: is the scaled height
* Parameter $qz: is the name prefix of the new picture
               * Return value: It is the name of the zoomed image, if it fails, it returns false
*
          */ 
         function thumb($name, $width, $height, $qz="th_"){
//Get picture information
                $imgInfo=$this->getInfo($name); //Width, height, type of image
//Get image resources, resources can be created for various types of pictures jpg, gif, png
                 $srcImg=$this->getImg($name, $imgInfo);
//Get the size of the image after calculating the equal proportions, $size["width"], $size["height"]
$size=$this->getNewSize($name, $width, $height, $imgInfo);
//Get new image resources and process the gif transparent background
                $newImg=$this->kidOfImage($srcImg, $size, $imgInfo);
//Save as a new image and return the new scaled image name
                  return $this->createNewImage($newImg, $qz.$name, $imgInfo);                                           } 

         private function createNewImage($newImg, $newName, $imgInfo){
              switch($imgInfo["type"]){
case 1://gif
                         $result=imageGif($newImg, $this->path.$newName);
break;
case 2://jpg
                          $result=imageJPEG($newImg, $this->path.$newName);
break;
case 3://png
                                $return=imagepng($newImg, $this->path.$newName);
break;
                                                                                                                                                    imagedestroy($newImg);
               return $newName;
         } 

        private function kidOfImage($srcImg, $size, $imgInfo){ 
            $newImg=imagecreatetruecolor($size["width"], $size["height"]); 
             
            $otsc=imagecolortransparent($srcImg); 
 
            if($otsc >=0 && $otsc                 $tran=imagecolorsforindex($srcImg, $otsc); 
 
                $newt=imagecolorallocate($newImg, $tran["red"], $tran["green"], $tran["blue"]); 
 
                imagefill($newImg, 0, 0, $newt); 
 
                imagecolortransparent($newImg, $newt); 
            } 
 
            imagecopyresized($newImg, $srcImg, 0, 0, 0, 0, $size["width"], $size["height"], $imgInfo["width"], $imgInfo["height"]); 
 
            imagedestroy($srcImg); 
 
            return $newImg; 
        } 
 
        private function getNewSize($name, $width, $height, $imgInfo){ 
            $size["width"]=$imgInfo["width"]; 
            $size["height"]=$imgInfo["height"]; 
 
            //缩放的宽度如果比原图小才重新设置宽度  
            if($width                 $size["width"]=$width; 
            } 
            //缩放的高度如果比原图小才重新设置高度  
            if($height                 $size["height"]=$height; 
            } 
 
            //图片等比例缩放的算法  
            if($imgInfo["width"]*$size["width"] > $imgInfo["height"] * $size["height"]){ 
                $size["height"]=round($imgInfo["height"]*$size["width"]/$imgInfo["width"]); 
            }else{ 
                $size["width"]=round($imgInfo["width"]*$size["height"]/$imgInfo["height"]); 
            } 
 
 
            return $size; 
 
        } 
 
        private function getInfo($name){ 
            $data=getImageSize($this->path.$name); 
 
            $imageInfo["width"]=$data[0]; 
            $imageInfo["height"]=$data[1]; 
            $imageInfo["type"]=$data[2]; 
 
            return $imageInfo; 
        } 
 
        private function getImg($name, $imgInfo){ 
            $srcPic=$this->path.$name; 
 
            switch($imgInfo["type"]){ 
                case 1: //gif  
                    $img=imagecreatefromgif($srcPic); 
                    break; 
                case 2: //jpg  
                    $img=imageCreatefromjpeg($srcPic); 
                    break; 
                case 3: //png  
                    $img=imageCreatefrompng($srcPic); 
                    break; 
                default: 
                    return false; 
                 
            } 
 
            return $img; 
        } 
        /* 功能:为图片加水印图片
         * 参数$groundName: 背景图片,即需要加水印的图片
         * 参数$waterName: 水钱图片
         * 参数#aterPost:水印位置, 10种状态, 
         *  0为随机位置
         *
         *  1. 为顶端居左  2. 为顶端居中  3 为顶端居右
         *  4  为中部居左  5. 为中部居中  6 为中部居右
         *  7 . 为底端居左 8. 为底端居中, 9. 为底端居右
         *
         * 参数$qz : 是加水印后的图片名称前缀
         * 返回值:就是处理后图片的名称
         *
         */ 
        function waterMark($groundName, $waterName, $waterPos=0, $qz="wa_"){ 
         
            if(file_exists($this->path.$groundName) && file_exists($this->path.$waterName)){ 
                $groundInfo=$this->getInfo($groundName); 
                $waterInfo=$this->getInfo($waterName); 
                //水印的位置  
                if(!$pos=$this->position($groundInfo, $waterInfo, $waterPos)){ 
                    echo "水印不应该比背景图片小!"; 
                    return; 
                } 
 
                $groundImg=$this->getImg($groundName, $groundInfo); 
                $waterImg=$this->getImg($waterName, $waterInfo); 
 
                $groundImg=$this->copyImage($groundImg, $waterImg, $pos, $waterInfo); 
 
                return $this->createNewImage($groundImg, $qz.$groundName, $groundInfo); 
            }else{ 
                echo "图片或水印图片不存在"; 
                return false; 
            } 
        } 
 
        private function copyImage($groundImg, $waterImg, $pos, $waterInfo){ 
            imagecopy($groundImg, $waterImg, $pos["posX"], $pos["posY"], 0, 0, $waterInfo["width"], $waterInfo["height"]); 
            imagedestroy($waterImg); 
 
            return $groundImg; 
        } 
         
        private function position($groundInfo, $waterInfo, $waterPos){ 
            //需要背景比水印图片大  
            if(($groundInfo["width"]                 return false; 
            } 
 
            switch($waterPos){ 
                case 1: 
                    $posX=0; 
                    $posY=0; 
                    break; 
                case 2: 
                    $posX=($groundInfo["width"]-$waterInfo["width"])/2; 
                    $posY=0; 
                    break; 
                case 3: 
                    $posX=$groundInfo["width"]-$waterInfo["width"]; 
                    $posY=0; 
                    break; 
                case 4: 
                    $posX=0; 
                    $posY=($groundInfo["height"]-$waterInfo["height"]) /2; 
                    break; 
                case 5: 
                    $posX=($groundInfo["width"]-$waterInfo["width"])/2; 
                    $posY=($groundInfo["height"]-$waterInfo["height"]) /2; 
                    break; 
                case 6: 
                    $posX=$groundInfo["width"]-$waterInfo["width"]; 
                    $posY=($groundInfo["height"]-$waterInfo["height"]) /2; 
                    break; 
                case 7: 
                    $posX=0; 
                    $posY=$groundInfo["height"]-$waterInfo["height"]; 
                    break; 
                case 8: 
                    $posX=($groundInfo["width"]-$waterInfo["width"])/2; 
                    $posY=$groundInfo["height"]-$waterInfo["height"]; 
                    break; 
                case 9: 
                    $posX=$groundInfo["width"]-$waterInfo["width"]; 
                    $posY=$groundInfo["height"]-$waterInfo["height"]; 
                    break; 
                case 0: 
                default: 
                    $posX=rand(0, ($groundInfo["width"]-$waterInfo["width"])); 
                    $posY=rand(0, ($groundInfo["height"]-$waterInfo["height"])); 
                    break; 
            } 
 
            return array("posX"=>$posX, "posY"=>$posY); 
        } 
 
    } 
 class Image {
  private $path;
  //构造方法用来对图片所在位置进行初使化
  function __construct($path="./"){
   $this->path=rtrim($path, "/")."/";
  }
  /* 对图片进行缩放
   *
* Parameter $name: is the name of the image that needs to be processed
* Parameter $width: is the width after scaling
* Parameter $height: is the scaled height
* Parameter $qz: is the name prefix of the new picture
* Return value: It is the name of the zoomed image. If it fails, it returns false
*
*/
function thumb($name, $width, $height, $qz="th_"){
//Get picture information
$imgInfo=$this->getInfo($name); //Width, height, type of image
//Get picture resources, you can create resources for various types of pictures jpg, gif, png
$srcImg=$this->getImg($name, $imgInfo);
//Get the size of the image after calculating the equal proportions, $size["width"], $size["height"]
$size=$this->getNewSize($name, $width, $height, $imgInfo);
//Get new image resources and process the gif transparent background
$newImg=$this->kidOfImage($srcImg, $size, $imgInfo);
//Save as a new picture and return the new scaled picture name
Return $this->createNewImage($newImg, $qz.$name, $imgInfo);
}

private function createNewImage($newImg, $newName, $imgInfo){
switch($imgInfo["type"]){
case 1://gif
$result=imageGif($newImg, $this->path.$newName);
Break;
case 2://jpg
$result=imageJPEG($newImg, $this->path.$newName);
Break;
case 3://png
$return=imagepng($newImg, $this->path.$newName);
Break;
}
Imagedestroy($newImg);
Return $newName;
}

private function kidOfImage($srcImg, $size, $imgInfo){
$newImg=imagecreatetruecolor($size["width"], $size["height"]);
 
$otsc=imagecolortransparent($srcImg);

if($otsc >=0 && $otsc $tran=imagecolorsforindex($srcImg, $otsc);

$newt=imagecolorallocate($newImg, $tran["red"], $tran["green"], $tran["blue"]);

imagefill($newImg, 0, 0, $newt);

imagecolortransparent($newImg, $newt);
}

imagecopyresized($newImg, $srcImg, 0, 0, 0, 0, $size["width"], $size["height"], $imgInfo["width"], $imgInfo["height"] );

imagedestroy($srcImg);

return $newImg;
}

private function getNewSize($name, $width, $height, $imgInfo){
$size["width"]=$imgInfo["width"];
$size["height"]=$imgInfo["height"];

//If the zoomed width is smaller than the original image, reset the width
if($width $size["width"]=$width;
}
//If the zoomed height is smaller than the original image, reset the height
if($height $size["height"]=$height;
}

//Algorithm for image scaling
if($imgInfo["width"]*$size["width"] > $imgInfo["height"] * $size["height"]){
$size["height"]=round($imgInfo["height"]*$size["width"]/$imgInfo["width"]);
}else{
$size["width"]=round($imgInfo["width"]*$size["height"]/$imgInfo["height"]);
}


Return $size;

}

private function getInfo($name){
$data=getImageSize($this->path.$name);

$imageInfo["width"]=$data[0];
$imageInfo["height"]=$data[1];
$imageInfo["type"]=$data[2];

return $imageInfo;
}

private function getImg($name, $imgInfo){
$srcPic=$this->path.$name;

switch($imgInfo["type"]){
Case 1: //gif
$img=imagecreatefromgif($srcPic);
Break;
Case 2: //jpg
$img=imageCreatefromjpeg($srcPic);
Break;
Case 3: //png
$img=imageCreatefrompng($srcPic);
Break;
Default:
Return false;
 
}

return $img;
}
/* Function: Add watermark to pictures
* Parameter $groundName: background image, that is, the image that needs to be watermarked
* Parameter $waterName: water money picture
* Parameter #aterPost: watermark position, 10 states,
* 0 is a random position
*
* 1. For top left 2. For top center 3 For top right
* 4 means the middle is on the left 5. means the middle is in the middle 6 means the middle is on the right
* 7. The bottom is on the left, 8. The bottom is in the middle, 9. The bottom is on the right
*
* Parameter $qz: is the watermarked image name prefix
* Return value: It is the name of the processed image
*
*/
function waterMark($groundName, $waterName, $waterPos=0, $qz="wa_"){

If(file_exists($this->path.$groundName) && file_exists($this->path.$waterName)){
$groundInfo=$this->getInfo($groundName);
$waterInfo=$this->getInfo($waterName);
//Position of watermark
If(!$pos=$this->position($groundInfo, $waterInfo, $waterPos)){
echo "The watermark should not be smaller than the background image!";
Return;
}

$groundImg=$this->getImg($groundName, $groundInfo);
$waterImg=$this->getImg($waterName, $waterInfo);

$groundImg=$this->copyImage($groundImg, $waterImg, $pos, $waterInfo);

return $this->createNewImage($groundImg, $qz.$groundName, $groundInfo);
}else{
echo "The picture or watermark image does not exist";
Return false;
}
}

private function copyImage($groundImg, $waterImg, $pos, $waterInfo){
Imagecopy($groundImg, $waterImg, $pos["posX"], $pos["posY"], 0, 0, $waterInfo["width"], $waterInfo["height"]);
Imagedestroy($waterImg);

return $groundImg;
}

Private function position($groundInfo, $waterInfo, $waterPos){
//The background needs to be larger than the watermark image
if(($groundInfo["width"] Return false;
}

   switch($waterPos){
    case 1:
     $posX=0;
     $posY=0;
     break;
    case 2:
     $posX=($groundInfo["width"]-$waterInfo["width"])/2;
     $posY=0;
     break;
    case 3:
     $posX=$groundInfo["width"]-$waterInfo["width"];
     $posY=0;
     break;
    case 4:
     $posX=0;
     $posY=($groundInfo["height"]-$waterInfo["height"]) /2;
     break;
    case 5:
     $posX=($groundInfo["width"]-$waterInfo["width"])/2;
     $posY=($groundInfo["height"]-$waterInfo["height"]) /2;
     break;
    case 6:
     $posX=$groundInfo["width"]-$waterInfo["width"];
     $posY=($groundInfo["height"]-$waterInfo["height"]) /2;
     break;
    case 7:
     $posX=0;
     $posY=$groundInfo["height"]-$waterInfo["height"];
     break;
    case 8:
     $posX=($groundInfo["width"]-$waterInfo["width"])/2;
     $posY=$groundInfo["height"]-$waterInfo["height"];
     break;
    case 9:
     $posX=$groundInfo["width"]-$waterInfo["width"];
     $posY=$groundInfo["height"]-$waterInfo["height"];
     break;
    case 0:
    default:
     $posX=rand(0, ($groundInfo["width"]-$waterInfo["width"]));
     $posY=rand(0, ($groundInfo["height"]-$waterInfo["height"]));
     break;
   }

   return array("posX"=>$posX, "posY"=>$posY);
  }

 }

 摘自 chaojie2009的专栏

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478376.htmlTechArticle?php class Image { private $path; //构造方法用来对图片所在位置进行初使化 function __construct($path=./){ $this-path=rtrim($path, /)./; } /* 对图片进行缩放...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),