PHP implements automatic scaling of uploaded pictures to the specified resolution and preserves clarity encapsulation class example

  • 2021-12-11 17:34:04
  • OfStack

This article illustrates the PHP implementation of automatically scaling uploaded pictures to the specified resolution and keeping the clarity of the encapsulation class. Share it for your reference, as follows:


class AutoImage{
  private $image;
  public function resize($src, $width, $height){
    //$src  Is  $_FILES['upload_image_file']['tmp_name']
    //$width And $height Is the specified resolution 
    // If you want to scale to the specified scale, you can set the $width And $height Replace with $src The specified proportion of 
    $this->image = $src;
    $info = getimagesize($src);// Get the true width, height and type of the picture 
    if($info[0] == $width && $info[1] == $height){
      // If the resolution 1 Sample, directly return to the original image 
      return $src;
    }
    switch ($info['mime']){
      case 'image/jpeg':
        header('Content-Type:image/jpeg');
        $image_wp = imagecreatetruecolor($width, $height);
        $image_src = imagecreatefromjpeg($src);
        imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
        imagedestroy($image_src);
        imagejpeg($image_wp,$this->image);
        break;
      case 'image/png':
        header('Content-Type:image/png');
        $image_wp = imagecreatetruecolor($width, $height);
        $image_src = imagecreatefrompng($src);
        imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
        imagedestroy($image_src);
        imagejpeg($image_wp,$this->image);
        break;
      case 'image/gif':
        header('Content-Type:image/gif');
        $image_wp = imagecreatetruecolor($width, $height);
        $image_src = imagecreatefromgif($src);
        imagecopyresampled($image_wp, $image_src, 0, 0, 0, 0, $width, $height, $info[0], $info[1]);
        imagedestroy($image_src);
        imagejpeg($image_wp,$this->image);
        break;
    }
    return $this->image;
  }
}

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of PHP Graphics and Pictures Operation Skills", "PHP Array (Array) Operation Skills", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Mathematical Operation Skills Summary", "php String (string) Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: