Two Examples of Image Compression Based on PHP

  • 2021-07-07 06:53:42
  • OfStack

This paper introduces two methods of PHP image compression. Readers can refer to or improve according to specific applications to adapt to their own application needs! Needless to say, the main code part is as follows:

Example 1:


<?php 
/** 
* desription  Compressed picture  
* @param sting $imgsrc  Picture path  
* @param string $imgdst  Save the path after compression  
*/
function image_png_size_add($imgsrc,$imgdst){ 
  list($width,$height,$type)=getimagesize($imgsrc); 
  $new_width = ($width>600?600:$width)*0.9; 
  $new_height =($height>600?600:$height)*0.9; 
  switch($type){ 
    case 1: 
      $giftype=check_gifcartoon($imgsrc); 
      if($giftype){ 
        header('Content-Type:image/gif'); 
        $image_wp=imagecreatetruecolor($new_width, $new_height); 
        $image = imagecreatefromgif($imgsrc); 
        imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
        imagejpeg($image_wp, $imgdst,75); 
        imagedestroy($image_wp); 
      } 
      break; 
    case 2: 
      header('Content-Type:image/jpeg'); 
      $image_wp=imagecreatetruecolor($new_width, $new_height); 
      $image = imagecreatefromjpeg($imgsrc); 
      imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
      imagejpeg($image_wp, $imgdst,75); 
      imagedestroy($image_wp); 
      break; 
    case 3: 
      header('Content-Type:image/png'); 
      $image_wp=imagecreatetruecolor($new_width, $new_height); 
      $image = imagecreatefrompng($imgsrc); 
      imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
      imagejpeg($image_wp, $imgdst,75); 
      imagedestroy($image_wp); 
      break; 
  } 
} 
/** 
* desription  Judge whether gif Animation  
* @param sting $image_file Picture path  
* @return boolean t  Yes  f  No  
*/
function check_gifcartoon($image_file){ 
  $fp = fopen($image_file,'rb'); 
  $image_head = fread($fp,1024); 
  fclose($fp); 
  return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true; 
} 
?>

Example 2:


<?php
/*
----------------------------------------------------------------------
 Function : Resize a picture or generate a thumbnail 
 Return :True/False
 Parameter :
  $Image   Pictures to be adjusted ( Path included )
  $Dw=450   Maximum width when adjusting ; Absolute width when thumbnail 
  $Dh=450   Maximum height during adjustment ; Absolute height when thumbnail 
  $Type=1  1, Adjust dimensions ; 2, Generate thumbnails 
$path='img/';// Path 
$phtypes=array(
  'img/gif',
  'img/jpg',
  'img/jpeg',
  'img/bmp',
  'img/pjpeg',
  'img/x-png'
);
Function Img($Image,$Dw=450,$Dh=450,$Type=1){
  IF(!File_Exists($Image)){
  Return False;
  }
  // If you need to generate thumbnails , Copy the original image 1 Give it again under $Image Assignment 
  IF($Type!=1){
  Copy($Image,Str_Replace(".","_x.",$Image));
  $Image=Str_Replace(".","_x.",$Image);
  }
  // Get the type of file , Create different objects according to different types 
  $ImgInfo=GetImageSize($Image);
  Switch($ImgInfo[2]){
  Case 1:
  $Img = @ImageCreateFromGIF($Image);
  Break;
  Case 2:
  $Img = @ImageCreateFromJPEG($Image);
  Break;
  Case 3:
  $Img = @ImageCreateFromPNG($Image);
  Break;
  }
  // If the object is not created successfully , Indicates that a non-picture file 
  IF(Empty($Img)){
  // If there is an error in generating thumbnails , You need to delete the files that have been copied 
  IF($Type!=1){Unlink($Image);}
  Return False;
  }
  // If the resizing operation is performed, 
  IF($Type==1){
  $w=ImagesX($Img);
  $h=ImagesY($Img);
  $width = $w;
  $height = $h;
  IF($width>$Dw){
   $Par=$Dw/$width;
   $width=$Dw;
   $height=$height*$Par;
   IF($height>$Dh){
   $Par=$Dh/$height;
   $height=$Dh;
   $width=$width*$Par;
   }
  }ElseIF($height>$Dh){
   $Par=$Dh/$height;
   $height=$Dh;
   $width=$width*$Par;
   IF($width>$Dw){
   $Par=$Dw/$width;
   $width=$Dw;
   $height=$height*$Par;
   }
  }Else{
   $width=$width;
   $height=$height;
  }
  $nImg = ImageCreateTrueColor($width,$height);   // New 1 A true color canvas 
  ImageCopyReSampled($nImg,$Img,0,0,0,0,$width,$height,$w,$h);// Resample and resize part of the copied image 
  ImageJpeg ($nImg,$Image);     // With JPEG Format to output images to browsers or files 
  Return True;
  // If you are performing a thumbnail generation operation, 
  }Else{
  $w=ImagesX($Img);
  $h=ImagesY($Img);
  $width = $w;
  $height = $h;
  $nImg = ImageCreateTrueColor($Dw,$Dh);
  IF($h/$w>$Dh/$Dw){ // The height ratio is large 
   $width=$Dw;
   $height=$h*$Dw/$w;
   $IntNH=$height-$Dh;
   ImageCopyReSampled($nImg, $Img, 0, -$IntNH/1.8, 0, 0, $Dw, $height, $w, $h);
  }Else{   // Width ratio is large 
   $height=$Dh;
   $width=$w*$Dh/$h;
   $IntNW=$width-$Dw;
   ImageCopyReSampled($nImg, $Img, -$IntNW/1.8, 0, 0, 0, $width, $Dh, $w, $h);
  }
  ImageJpeg ($nImg,$Image);
  Return True;
  }
}
?>
<html><body>
<form method="post" enctype="multipart/form-data" name="form1">
 <table>
  <tr><td> Upload pictures </td></tr>
  <tr><td><input type="file" name="photo" size="20" /></td></tr>
 <tr><td><input type="submit" value=" Upload "/></td></tr>
 </table>
  The file types allowed to upload are :<?=implode(', ',$phtypes)?></form>
<?php
 if($_SERVER['REQUEST_METHOD']=='POST'){
  if (!is_uploaded_file($_FILES["photo"][tmp_name])){
   echo " Picture does not exist ";
   exit();
  }
  if(!is_dir('img')){// If the path does not exist, create 
   mkdir('img');
  }
  $upfile=$_FILES["photo"]; 
  $pinfo=pathinfo($upfile["name"]);
  $name=$pinfo['basename'];// Filename 
  $tmp_name=$upfile["tmp_name"];
  $file_type=$pinfo['extension'];// Get the file type 
  $showphpath=$path.$name;
  
  if(in_array($upfile["type"],$phtypes)){
   echo " File type mismatch! ";
   exit();
   }
  if(move_uploaded_file($tmp_name,$path.$name)){
  echo " Success! ";
 Img($showphpath,100,800,2);
  }
  echo "<img src=\"".$showphpath."\" />";
 }
?>
</body>
</html>

Related articles: