Home Backend Development PHP Tutorial PHP image operation class, supports generating thumbnails, adding watermarks, and uploading thumbnails

PHP image operation class, supports generating thumbnails, adding watermarks, and uploading thumbnails

Nov 29, 2016 am 11:08 AM
php

<?php
/**
 * @author wolf
 *
 */
class Image {
    //类开始
    public $originimage = ""; //源图片文件地址
    public $imageext = ""; //源图片格式
    public $thumbimage = ""; //缩略图文件存放地址
    public $thumb_maxwidth = 1440; //缩略图最大宽度
    public $thumb_maxheight = 900; //缩略图最大高度
    public $watermark_text = ""; //水印文字内容
    public $watermark_minwidth = 300; //源图片最小宽度:大于此值时加水印
    public $watermark_minheight = 200; //源图片最小高度:大于此值时加水印
    public $watermark_fontfile = ""; //字体文件
    public $watermark_fontsize = 14; //字体大小
    public $watermark_logo = "config/water.png"; //水印LOGO地址
    public $watermark_transparent = 20; //水印LOGO不透明度
    private $origin_width = 0; //源图片宽度
    private $origin_height = 0; //源图片高度
    private $imageQuilty = 90; //图片质量
    private $tmp_originimage = ""; //临时图片(源图片)
    private $tmp_thumbimage = ""; //临时图片(缩略图)
    private $tmp_waterimage = ""; //临时图片(水印LOGO)
    private $_waterPosition = 2; //1正中间 2右下角
    //生成缩略图
    public function gen_thumbimage() {
        if ($this->originimage == "" || $this->thumbimage == "") {
            return 0;
        }
        $this->get_oriwidthheight ();
        if ($this->origin_width < $this->thumb_maxwidth && $this->origin_height < $this->thumb_maxheight) {
            $this->thumb_maxwidth = $this->origin_width;
            $this->thumb_maxheight = $this->origin_height;
        } else {
            if ($this->origin_width < $this->origin_height) {
                $this->thumb_maxwidth = ($this->thumb_maxheight / $this->origin_height) * $this->origin_width;
            } else {
                $this->thumb_maxheight = ($this->thumb_maxwidth / $this->origin_width) * $this->origin_height;
            }
        }
        $this->get_imagetype ();
        $this->gen_tmpimage_origin ();
        $this->gen_tmpimage_thumb ();
        if ($this->tmp_originimage == "" || $this->tmp_thumbimage == "") {
            return - 1;
        }
        imagecopyresampled ( $this->tmp_thumbimage, $this->tmp_originimage, 0, 0, 0, 0, $this->thumb_maxwidth, $this->thumb_maxheight, $this->origin_width, $this->origin_height );
        switch ($this->imageext) {
            case "gif" :
                imagegif ( $this->tmp_thumbimage, $this->thumbimage );
                return 1;
                break;
            case "jpg" :
                imagejpeg ( $this->tmp_thumbimage, $this->thumbimage, $this->imageQuilty );
                return 2;
                break;
            case "png" :
                imagepng ( $this->tmp_thumbimage, $this->thumbimage );
                return 3;
                break;
            default :
                return - 2;
                break;
        }
    }
    //添加文字水印
    public function add_watermark1() {
        if ($this->originimage == "" || $this->watermark_text == "" || $this->watermark_fontfile == "") {
            return 0;
        }
        $this->get_oriwidthheight ();
        if ($this->origin_width < $this->watermark_minwidth || $this->origin_height < $this->watermark_minheight) {
            return 0;
        }
        $this->get_imagetype ();
        $this->gen_tmpimage_origin ();
        if ($this->tmp_originimage == "") {
            return - 1;
        }
        $textcolor = imagecolorallocate ( $this->tmp_originimage, 255, 0, 0 );
        $angle = 0;
        $px = $this->origin_width / 2 - 200;
        $py = $this->origin_height / 2 - 10;
        imagettftext ( $this->tmp_originimage, $this->watermark_fontsize, $angle, $px, $py, $textcolor, $this->watermark_fontfile, $this->watermark_text );
        switch ($this->imageext) {
            case "gif" :
                imagegif ( $this->tmp_originimage, $this->originimage );
                return 1;
                break;
            case "jpg" :
                imagejpeg ( $this->tmp_originimage, $this->originimage, $this->imageQuilty );
                return 2;
                break;
            case "png" :
                imagepng ( $this->tmp_originimage, $this->originimage );
                return 3;
                break;
            default :
                return - 2;
                break;
        }
    }
    //添加LOGO水印
    public function add_watermark2() {
        if ($this->originimage == "" || $this->watermark_logo == "") {
            return 0;
        }
        $this->get_oriwidthheight ();
        if ($this->origin_width < $this->watermark_minwidth || $this->origin_height < $this->watermark_minheight) {
            return 0;
        }
        $this->get_imagetype ();
        $this->gen_tmpimage_origin ();
        $this->gen_tmpimage_waterlogo ();
        if ($this->tmp_originimage == "" || $this->tmp_waterimage == "") {
            return - 1;
        }
        list ( $logo_width, $logo_height ) = getimagesize ( $this->watermark_logo );
        //正中间
        $waterZb = $this->waterPosition ( $logo_width, $logo_height );
        $px = $waterZb [&#39;x&#39;];
        $py = $waterZb [&#39;y&#39;];
        imagecopymerge ( $this->tmp_originimage, $this->tmp_waterimage, $px, $py, 0, 0, $logo_width, $logo_height, $this->watermark_transparent );
        switch ($this->imageext) {
            case "gif" :
                imagegif ( $this->tmp_originimage, $this->originimage );
                return 1;
                break;
            case "jpg" :
                imagejpeg ( $this->tmp_originimage, $this->originimage, $this->imageQuilty );
                return 2;
                break;
            case "png" :
                imagepng ( $this->tmp_originimage, $this->originimage );
                return 3;
                break;
            default :
                return - 2;
                break;
        }
    }
      
    /**
     * 上传缩略图
     * 注意上传文件大小限制
     *@param String $files $_FILES[&#39;upload&#39;] 类型
     *@param String  $path  存储的目录 默认在/static/attached/
     *@param boolean $isWater 是否添加水印
     * @return string $filePath 网页url图片路径
     */
    public function upload($files, $path, $isWater) {
        if (is_uploaded_file ( $files [&#39;tmp_name&#39;] )) {
            $upfile = $files;
            $name = $upfile [name];
            $type = $upfile [type];
            $size = $upfile [size];
            $tmp_name = $upfile [tmp_name];
            $error = $upfile [error];
              
            if ($size > 1048576) {
                return array (&#39;status&#39; => false, &#39;message&#39; => "$name图片太大超过1MB" );
            }
              
            $rs = $this->getImageSize ( $tmp_name );
            if (! $rs [&#39;status&#39;]) {
                $rs [&#39;message&#39;] = $name . $rs [&#39;message&#39;];
                return $rs;
            }
              
            // 创建文件夹
            $save_path = getcwd () . "/static/attached/" . $path . "/";
            $save_url = "./static/attached/" . $path . "/";
            $ym = date ( "Ym" );
            $save_path .= $ym . "/";
            $save_url .= $ym . "/";
            if (! file_exists ( $save_path )) {
                mkdir ( $save_path );
            }
              
            if ($error == &#39;0&#39;) {
                $fileType = substr ( $name, strpos ( $name, "." ) + 1 );
                $prefix = $this->getRandPrefix ();
                $newName = date ( "YmdHi" ) . $prefix . "." . $fileType;
                $filepath = $save_path . $newName;
                move_uploaded_file ( $tmp_name, $filepath );
              
            }
              
            if ($isWater) {
                $this->water ( $filepath );
            }
              
            return array (&#39;status&#39; => true, &#39;message&#39; => $save_url . $newName );
        }
    }
      
    /**
     * 图片增加水印处理
     * @param unknown_type $image
     */
    public function water($image) {
        $this->watermark_logo = ROOT . $this->watermark_logo;
        $this->originimage = $image;
        //LOGO水印
        $this->add_watermark2 ();
    }
      
    /**
     * 
     * 获取随机前缀
     */
    private function getRandPrefix() {
        $string = "abcdefghijklmnopqrstuvwxyz0123456789";
        $prefix = &#39;&#39;;
        for($i = 0; $i < 4; $i ++) {
            $rand = rand ( 0, 33 );
            $prefix .= $string {$rand};
        }
        return $prefix;
    }
      
    //检测图片大小
    private function getImageSize($image) {
        list ( $width, $height, $type, $attr ) = getimagesize ( $image );
          
        if ($type != 2 && $type != 3) {
            return array (&#39;status&#39; => false, &#39;message&#39; => "图片格式不正确,请上传JPG或者PNG图片" . $type );
        }
        //检测图片大小
        if ($width > 1440) {
            return array (&#39;status&#39; => false, &#39;message&#39; => "图片宽度请小于1440px,当前为" . $width . "px" );
        }
          
        if ($height > 900) {
            return array (&#39;status&#39; => false, &#39;message&#39; => "图片高度请小于900px,当前为" . $height . "px" );
          
        }
        return array (&#39;status&#39; => true );
    }
      
    /**
     * 生成缩略图
     * 
     * @param String $imagefile 原始文件
     * @param String $thumbWidth  缩略图宽度
     * @param String $thumbHeight 缩略图高度
     * @return String 缩略图url         
     */
    public function reduceImage($imagefile, $thumbWidth, $thumbHeight, $path = "thumb") {
          
        // 生成缩略图
        $dir = date ( "Ym", time () );
        $imagefile = ROOT . $imagefile;
        $imagefile_s = ROOT . "static/attached/" . $path . "/" . $dir . "/s_" . basename ( $imagefile );
        $imagetrans = new Image ();
        $imagetrans->originimage = $imagefile;
        $imagetrans->thumbimage = $imagefile_s;
        $imagetrans->thumb_maxwidth = $thumbWidth;
        $imagetrans->thumb_maxheight = $thumbHeight;
        $isokid = $imagetrans->gen_thumbimage ();
          
        return "./static/attached/" . $path . "/" . $dir . "/s_" . basename ( $imagefile );
      
    }
    /**
     * 水印位置
     * @param int $logo_width
     * @param int $logo_height
     * @return 水印坐标
     */
    private function waterPosition($logo_width, $logo_height) {
        switch ($this->_waterPosition) {
            case 1 :
                $px = $this->origin_width / 2 - $logo_width / 2;
                $py = $this->origin_height / 2 - $logo_height / 2;
                break;
            case 2 :
                $px = $this->origin_width - $logo_width - 10;
                $py = $this->origin_height - $logo_height - 10;
                break;
            default :
                $px = $this->origin_width / 2 - $logo_width / 2;
                $py = $this->origin_height / 2 - $logo_height / 2;
                break;
        }
          
        return array (&#39;x&#39; => $px, &#39;y&#39; => $py );
    }
    //获取图片尺寸
    private function get_oriwidthheight() {
        list ( $this->origin_width, $this->origin_height ) = getimagesize ( $this->originimage );
        return 1;
    }
    /*
     * 检测图片格式
     * 原方法需要开启exif 扩展
     */
    private function get_imagetype() {
        $ext = $this->getImgext ( $this->originimage );
        switch ($ext) {
            case 1 :
                $this->imageext = "gif";
                break;
            case 2 :
                $this->imageext = "jpg";
                break;
            case 3 :
                $this->imageext = "png";
                break;
            default :
                $this->imageext = "unknown";
                break;
        }
    }
    //创建临时图片(源图片)
    private function gen_tmpimage_origin() {
        $ext = $this->getImgext ( $this->originimage );
        switch ($ext) {
            case 1 :
                $this->tmp_originimage = imagecreatefromgif ( $this->originimage );
                $bgcolor = imagecolorallocate ( $this->tmp_originimage, 0, 0, 0 );
                $bgcolortrans = imagecolortransparent ( $this->tmp_originimage, $bgcolor );
                break;
            case 2 :
                $this->tmp_originimage = imagecreatefromjpeg ( $this->originimage );
                break;
            case 3 :
                $this->tmp_originimage = imagecreatefrompng ( $this->originimage );
                imagesavealpha ( $this->tmp_originimage, true );
                break;
            default :
                $this->tmp_originimage = "";
                break;
        }
    }
    //创建临时图片(缩略图)
    private function gen_tmpimage_thumb() {
        $ext = $this->getImgext ( $this->originimage );
        switch ($ext) {
            case 1 :
                $this->tmp_thumbimage = imagecreatetruecolor ( $this->thumb_maxwidth, $this->thumb_maxheight );
                $bgcolor = imagecolorallocate ( $this->tmp_thumbimage, 255, 255, 255 );
                imagefill ( $this->tmp_thumbimage, 0, 0, $bgcolor );
                break;
            case 2 :
                $this->tmp_thumbimage = imagecreatetruecolor ( $this->thumb_maxwidth, $this->thumb_maxheight );
                break;
            case 3 :
                $this->tmp_thumbimage = imagecreatetruecolor ( $this->thumb_maxwidth, $this->thumb_maxheight );
                $bgcolor = imagecolorallocate ( $this->tmp_thumbimage, 255, 255, 255 );
                imagefill ( $this->tmp_thumbimage, 0, 0, $bgcolor );
                imagealphablending ( $this->tmp_thumbimage, false );
                imagesavealpha ( $this->tmp_thumbimage, true );
                break;
            default :
                $this->tmp_thumbimage = "";
                break;
        }
    }
    //创建临时图片(LOGO水印)
    private function gen_tmpimage_waterlogo() {
        $ext = $this->getImgext ( $this->watermark_logo );
        switch ($ext) {
            case 1 :
                $this->tmp_waterimage = imagecreatefromgif ( $this->watermark_logo );
                $bgcolor = imagecolorallocate ( $this->tmp_waterimage, 0, 0, 0 );
                $bgcolortrans = imagecolortransparent ( $this->tmp_waterimage, $bgcolor );
                break;
            case 2 :
                $this->tmp_waterimage = imagecreatefromjpeg ( $this->watermark_logo );
                break;
            case 3 :
                $this->tmp_waterimage = imagecreatefrompng ( $this->watermark_logo );
                imagesavealpha ( $this->tmp_waterimage, true );
                break;
            default :
                $this->tmp_waterimage = "";
                break;
        }
    }
    /*
     * 获取后缀名
     */
    public function getImgext($filename) {
        return exif_imagetype ( $filename );
    }
    //释放资源
    public function __destruct() {
        if (is_object ( $this->tmp_originimage ) == true) {
            imagedestroy ( $this->tmp_originimage );
        }
        if (is_object ( $this->tmp_thumbimage ) == true) {
            imagedestroy ( $this->tmp_thumbimage );
        }
        if (is_object ( $this->tmp_waterimage ) == true) {
            imagedestroy ( $this->tmp_waterimage );
        }
    }
}
Copy after login


Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles