search
HomeBackend DevelopmentPHP Tutorialphp thumbnail class (with calling example)

This article introduces a thumbnail class implemented in PHP that supports loading image files and image strings, proportional stretching, etc. There are calling examples behind the code for reference.

Share a php thumbnail class that can achieve the following functions:

1. Support loading image files and loading image strings 2. You can output thumbnails to the browser and keep thumbnail files 3. Support gif, png, jpeg type abbreviations 4. You can set whether to stretch proportionally

The code is as follows:

<?php
/**
 * 生成缩略图(支持加载图片文件和字符串2种方式)
 * @param       $maxWidth       缩略图最大宽度
 * @param       $maxHeight      缩略图最大高度
 * @param       bool    $scale  是否按比例缩小,否则拉伸
 * @param       bool    $inflate        是否放大以来填充缩略图
 * @edit by bbs.it-home.org
 */
class Thumbnail {
        private $maxWidth;
        private $maxHeight;
        private $scale;
        private $inflate;
        private $types;
        private $imgLoaders;
        private $imgCreators;
        private $source;
        private $sourceWidth;
        private $sourceHeight;
        private $sourceMime;
        private $thumb;
        private $thumbWidth;
        private $thumbHeight;

        public function __construct($maxWidth, $maxHeight, $scale = true, $inflate = true) {
                $this->maxWidth = $maxWidth;
                $this->maxHeight = $maxHeight;
                $this->scale = $scale;
                $this->inflate = $inflate;
                $this->types = array(
                    'image/jpeg',
                    'image/png',
                    'image/gif'
                );
                //加载MIME类型图像的函数名称
                $this->imgLoaders = array(
                    'image/jpeg'        =>      'imagecreatefromjpeg',
                    'image/png'         =>      'imagecreatefrompng',
                    'image/gif'         =>      'imagecreatefromgif'
                );
                //储存创建MIME类型图片的函数名称
                $this->imgCreators = array(
                    'image/jpeg'        =>      'imagejpeg',
                    'image/png'         =>      'imagepng',
                    'image/gif'         =>      'imagegif'
                );           
        }
        /**
         * 文件方式加载图片
         * @param       string  $image 源图片
         * @return      bool    
         */
        public function loadFile($image){
                if(!$dims = @getimagesize($image)){
                        trigger_error("源图片不存在");
                }
                if(in_array($dims['mime'], $this->types)){
                        $loader = $this->imgLoaders[$dims['mime']];
                        $this->source = $loader($image);
                        $this->sourceWidth = $dims[0];
                        $this->sourceHeight = $dims[1];
                        $this->sourceMime = $dims['mime'];
                        $this->initThumb();
                        return TRUE;
                }else{
                        trigger_error('不支持'.$dims['mime']."图片类型");
                }
        }
        /**
         * 字符串方式加载图片
         * @param       string $image  字符串
         * @param       string $mime    图片类型
         * @return type 
         */
        public function loadData($image,$mime){
                if(in_array($mime, $this->types)){
                        if($this->source = @imagecreatefromstring($image)){
                                $this->sourceWidth = imagesx($this->source);
                                $this->sourceHeight = imagesy($this->source);
                                $this->sourceMime = $mime;
                                $this->initThumb();
                                return TRUE;
                        }else{
                                trigger_error("不能从字符串加载图片");
                        }
                }else{
                        trigger_error("不支持".$mime."图片格式");
                }
        }
        /**
         * 生成缩略图
         * @param       string  $file   文件名。如果不为空则储存为文件,否则直接输出到浏览器
         */
        public function buildThumb($file = null){
                $creator = $this->imgCreators[$this->sourceMime];
                if(isset($file)){
                        return $creator($this->thumb,$file);
                }else{
                        return $creator($this->thumb);
                }
        }
        /**
         * 处理缩放
         */
        public function initThumb(){
                if($this->scale){
                        if($this->sourceWidth > $this->sourceHeight){
                                $this->thumbWidth = $this->maxWidth;
                                $this->thumbHeight = floor($this->sourceHeight*($this->maxWidth/$this->sourceWidth));
                        }elseif($this->sourceWidth < $this->sourceHeight){
                                $this->thumbHeight = $this->maxHeight;
                                $this->thumbWidth = floor($this->sourceWidth*($this->maxHeight/$this->sourceHeight));
                        }else{
                                $this->thumbWidth = $this->maxWidth;
                                $this->thumbHeight = $this->maxHeight;
                        }
                }
                $this->thumb = imagecreatetruecolor($this->thumbWidth, $this->thumbHeight);
                
                if($this->sourceWidth <= $this->maxWidth && $this->sourceHeight <= $this->maxHeight && $this->inflate == FALSE){
                        $this->thumb = $this->source;
                }else{
                        imagecopyresampled($this->thumb, $this->source, 0, 0, 0, 0, $this->thumbWidth, $this->thumbHeight, 
$this->sourceWidth, $this->sourceHeight);
                }
        }
        
        public function getMine(){
                return $this->sourceMime;
        }
        
        public function getThumbWidth(){
                return $this->thumbWidth;
        }
        
        public function getThumbHeight(){
                return $this->thumbHeight;
        }

}

/**
 * 缩略图类调用示例(文件)
 */
$thumb = new Thumbnail(200, 200);
$thumb->loadFile('wap.gif');
header('Content-Type:'.$thumb->getMine());
$thumb->buildThumb();
/**
 * 缩略图类调用示例(字符串)
 */
$thumb = new Thumbnail(200, 200);
$image = file_get_contents('wap.gif');
$thumb->loadData($image, 'image/jpeg');
$thumb->buildThumb('wap_thumb.gif');
?>


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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools