


PHP file upload class can generate thumbnail code_PHP tutorial
php教程文件上传类可生成缩略图代码
if ($_GET['action'] == 'save') {
$up = new upload();
$up->set_dir(dirname(__FILE__).'/upload/','{y}/{m}');
$up->set_thumb(100,80);
$up->set_watermark(dirname(__FILE__).'/jblog/images/watermark.png',6,90);
$fs = $up->execute();
var_dump($fs);
}
?>
test
class upload { //Allow attachment types to be uploadedwww.bkjia.com
var $field; //Upload control name
var $maxsize; //Maximum allowed file size in KB
var $thumb_width; //Thumbnail width
var $thumb_height; //Thumbnail height
var $watermark_file; //Watermark image address var $watermark_pos; //Watermark position
var $watermark_trans;//Watermark transparency
//Constructor function
//$types: File types allowed to be uploaded, $maxsize: Allowed size, $field: Upload control name, $time: Custom upload time
function upload($types = 'jpg |png', $maxsize = 1024, $field = 'attach', $time = '') {
$this->allow_types = explode('|',$types);
$this-> ;maxsize = $maxsize * 1024;
//Set and create the directory where files are stored specifically. "
" //$basedir: Base directory, must be a physical path. d} 🎜> if (!emptyempty($filedir)) { ;time),date('m',$this->time),date('d',$this->time)),strtolower($filedir)); ',$filedir);
foreach ($dirs as $d) { !emptyempty($d) && $dir .= $d.'/';
!is_dir($dir) && @ mkdir($dir,0777); 🎜>
//Image thumbnail settings, no need to set if thumbnails are not generated
$this->thumb_width = $width; $this->thumb_height = $height; , if no watermark is generated, there is no need to set it.
//$file: watermark image, $pos: watermark position, $trans: watermark transparency
function set_watermark ($file, $pos = 6, $trans = 80) {
$this-> watermark_file = $file;
$this->watermark_pos = $pos;
$this->watermark_trans = $trans;
} > /*------- -------------------------------------------------- ------- Execute the file upload, and return a file information array containing a successful or failure of uploading or failure. If the upload fails, it is the local file name.
dir is the physical path to store the attachment on the server. If the upload fails, the value does not exist.
size is the size of the attachment. If the upload fails, the value does not exist. 1 means success, -1 means the file type is not allowed, -2 means the file size exceeds
--------------------------------- ------------------------------------*/ files = array(); //Successfully uploaded file information foreach ($keys as $key) { _FILES[$field]['name'][$key]); //Get the file extension
$filename = date('Ymdhis',$this->time).mt_rand(10,99).' . '. $ fileExt; // Generate file name
$ Filedir = $ this- & gt; dir; // The actual storage catalog of the attachment
$ Filesize = $ _Files [$ Field] [' SIZE '] [$ Key ]; //File size
$files[$key]['name'] = $_FILES[$field]['name'][$key];
$files[$key]['flag'] = -1;
continue;
}
//文件大小超出
if ($filesize > $this->maxsize) {
$files[$key]['name'] = $_FILES[$field]['name'][$key];
$files[$key]['name'] = $filesize;
$files[$key]['flag'] = -2;
continue;
}
$files[$key]['name'] = $filename;
$files[$key]['dir'] = $filedir;
$files[$key]['size'] = $filesize;
//保存上传文件并删除临时文件
if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {
move_uploaded_file($_FILES[$field]['tmp_name'][$key],$filedir.$filename);
@unlink($_FILES[$field]['tmp_name'][$key]);
$files[$key]['flag'] = 1;
//对图片进行加水印和生成缩略图
if (in_array($fileext,array('jpg','png'))) {
if ($this->thumb_width) {
if ($this->create_thumb($filedir.$filename,$filedir.'thumb_'.$filename)) {
$files[$key]['thumb'] = 'thumb_'.$filename; //缩略图文件名
}
}
$this->create_watermark($filedir.$filename);
}
//Create a thumbnail, generate a thumbnail with the same extension
//$src_file : Source image path, $thumb_file : Thumbnail path = $this->thumb_height;
//If the source image is less than or equal to the thumbnail then Copy the source image as a thumbnail if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {
if (!copy($src_file,$thumb_file)) {
; > // Calculate the thumbnail size proportionally src_info[1] - $t_height) { _width = ($t_height / $src_info [1]) * $src_info[0]; 🎜>
switch ($fileext) {
case 'gif' :
$src_img = ImageCreateFromGIF($src_file); break;
}
If the degree is good, priority will be given
if (function_exists('imagecopyresampled')) {
@ImageCopyResampled($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]) ; 🎜> }
b_img,$thumb_file); break;
ImageGIF($thumb_img,$thumb_file); break;
case 'png' :
ImagePNG($thumb_img,$thumb_file); break; Image @ I> // $ file: The file to add watermark
Function Create_watermark ($ File) {
// The file does not exist, and return
if (! File_exists ($ This- & GT; Watermark_file) || !file_exists($file)) return; $gd_allow_types = array();
if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF'; reateFromPNG ';
if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';
//获取文件信息
$fileinfo = getImageSize($file);
$wminfo = getImageSize($this->watermark_file);
if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;
if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {
if (array_key_exists($wminfo['mime'],$gd_allow_types)) {
//从文件创建图像
$temp = $gd_allow_types[$fileinfo['mime']]($file);
$temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);
//水印位置
switch ($this->watermark_pos) {
case 1 : //顶部居左
$dst_x = 0; $dst_y = 0; break;
case 2 : //顶部居中
$dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = 0; break;
case 3 : //顶部居右
$dst_x = $fileinfo[0]; $dst_y = 0; break;
case 4 : //底部居左
$dst_x = 0; $dst_y = $fileinfo[1]; break;
case 5 : //底部居中
$dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;
case 6 : //底部居右
$dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break; t_rand(0, $fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]); 'ImageAlphaBlending' )) ImageAlphaBlending($temp_wm,True); //Set the image blending mode
if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //Save the complete alpha channel information 🎜> x,$dst_y,0,0,$wminfo[0],$wminfo [1],$this->watermark_trans); info[1] );
case 'image/jpeg' : file); ,$file); imageGIF($temp,$file); //Destroy the zero-time image >
function fileext($filename) {
return strtolower(substr(strrchr($filename,'.'),1,10));
} }
}
http://www.bkjia.com/PHPjc/444941.html
true

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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,

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.

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

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

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
