Home Backend Development PHP Tutorial PHP image file upload class (can automatically generate thumbnails)

PHP image file upload class (can automatically generate thumbnails)

Jul 25, 2016 am 08:56 AM

分享一个php图片上传类,且可以自动生成缩略图,有需要的朋友,可以作个参考,希望可以对您有用。

php实现的图片文件上传类,代码:

<?php
/**
功 能:文件上传类 支持文件夹自动分组保存;
创建类:参数(文件域,文件原名,文件大小);
$myupload = new upfileClass($upfile,$upfile_name,$upfile_size);
$myupload->savefile(); # 保存方法 并返回保存路径附带文件名;

@ echo MakeBuild($BuildFile,$newFile,$File_width);
生成指定文件的缩略图;
$myupload->MakeBuild("images/a.jpg","news/b.jpg","100");
*/

class upfileClass
{
var $upfile, $upfile_name, $upfile_size;

var $new_upfile_name;   # 上传后的文件名称 ; 
var $fleth, $fileExtent; # 文件扩展名(类型) ; 
var $f1, $f2, $f3;   # 文件保存路径(多级) upfiles/2008-01/08/;
var $filename;    # 文件(带路径) ;

var $maxSize, $File_type; # 允许上传文件的大小 允许上传文件的类型 ;

var $BuildFile,$newFile,$File_width,$File_height,$rate;

function upfileClass($upfile,$upfile_name,$upfile_size)
{
   $this->upfile = $upfile;
  $this->upfile_name = $upfile_name;
  $this->upfile_size = $upfile_size;
  
  $this->new_upfile_name = $this->CreateNewFilename($this->upfile_name);
  
  $this->f1 = "upfiles";
  $this->f2 = $this->f1."/".date('Y')."-".date('m');
$this->f3 = $this->f2."/".date('d');
  
  $this->filename = $this->f3 . "/" . $this->new_upfile_name;
  $this->maxSize = 500*1024;    # 文件大小 500KB
  $this->File_type = "gif/jpg/jpeg/png"; # 允许上传的文件类型
}

# 创建新文件名 (原文件名)
function CreateNewFilename($file_name)
{
   $this->fleth = explode(".",$file_name);
   $this->fileExtent = $this->fleth[(int)count($this->fleth)-1]; # 获取文件后缀;
   $tmpstr = date('YmdHis') . "." .$this->fileExtent;    # 创建新文件名;
   return $tmpstr;
}

# 检测文件类型是否正确
function chk_fileExtent()
{
   $iwTrue = 0;
   $fle = explode("/",$this->File_type);
   for($i=0; $i < count($fle); $i++){
    if( $this->fileExtent == $fle[$i] )
    {
     $iwTrue = (int) $iwTrue + 1;
    }
   }
   if( $iwTrue == 0 ){
    $this->msg("文件不符合 ".$this->File_type." 格式!");
   }
}

# 提示错误信息并终止操作
function msg($Error)
{
   echo "<script language=/"javascript/">/n";
   echo " alert('".$Error."');/n";
   echo " window.history.back();/n";
   echo "</script>/n";
   die();
}

# 保存文件
function savefile()
{
   $this->chk_fileExtent();
   $this->chk_fileSize();
   $this->CreateFolder( "../".$this->f1 );
   $this->CreateFolder( "../".$this->f2 );
   $this->CreateFolder( "../".$this->f3 );
   return $this->chk_savefile();
}

# 检测上传结果是否成功
function chk_savefile()
{
   $copymsg = copy($this->upfile,"../".$this->filename);
   if( $copymsg ){
    return $this->filename;
   }
   else{
    $this->msg("文件上传失败! /n/n请重新上传! ");
   }
}

# 创建文件夹
function CreateFolder($foldername)
{
   if( !is_dir($foldername) ){
    mkdir($foldername,0777);
   }
}

# 检测文件大小
function chk_fileSize()
{
   if( $this->upfile_size > $this->maxSize ){
    $this->msg("目标文件不能大于". $this->maxSize/1024 ." KB");
   }
}

# 删除文件($filePath 文件相对路径)
function Deletefile($filePath)
{
   if( !is_file($filePath) ){
    return false;
   }
   else{
    $ending = @unlink($filePath);
    return $ending;
   }
}

/*
   函数:生成缩略图
    MakeBuild("images/a.jpg","news/b.jpg","100");
   参数:
   echo $BuildFile;   原图 带路径
   echo $newFile;    生成的缩略图 带路径
   echo $File_width;   缩略图宽度值
   echo $File_height;   缩略图高度值 (默认为宽度的比例值)
   echo $rate;     缩略图象品质;
*/
function MakeBuild($BuildFile,$newFile,$File_width,$File_height=0,$rate=100) 
{ 
   if(!is_file($BuildFile)){
    $this->msg("文件 ".$BuildFile." 不是一个有效的图形文件!/n/n系统无法生成该文件的缩略图!");
    return false;
   }
   $data = GetImageSize($BuildFile); 
   switch($data[2]){ 
   case 1: 
    $im = @ImageCreateFromGIF($BuildFile); 
    break;
   case 2: 
    $im = @ImageCreateFromJPEG($BuildFile); 
    break;
   case 3: 
    $im = @ImageCreateFromPNG($BuildFile); 
    break;
   } 
   if(!$im){
    return false;
   }
   else{
    $srcW=ImageSX($im);  # 取得原图宽度;
    $srcH=ImageSY($im); # 取得原图高度;
    $dstX=0; 
    $dstY=0; 
   
    if($File_height==0){
     $File_height = $File_width/$srcW*$srcH;
    }
   
    if ($srcW*$File_height>$srcH*$File_width){ 
     $fFile_height = round($srcH*$File_width/$srcW); 
     $dstY = floor(($File_height-$fFile_height)/2); 
     $fFile_width = $File_width; 
    } 
    else { 
     $fFile_width = round($srcW*$File_height/$srcH); 
     $dstX = floor(($File_width-$fFile_width)/2); 
     $fFile_height = $File_height; 
    } 
    $ni = ImageCreateTrueColor($File_width,$File_height); 
    $dstX = ($dstX<0)?0:$dstX; 
    $dstY = ($dstX<0)?0:$dstY; 
    $dstX = ($dstX>($File_width/2))?floor($File_width/2):$dstX; 
    $dstY = ($dstY>($File_height/2))?floor($File_height/s):$dstY; 
    ImageCopyResized($ni,$im,$dstX,$dstY,0,0,$fFile_width,$fFile_height,$srcW,$srcH); 
   
    ImageJpeg($ni,$newFile,$rate); # 生成缩略图;
    imagedestroy($im);     # imagedestroy(resource) 释放image关联的内存
   }
} 

}
?>
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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

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,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles