search
HomeBackend DevelopmentPHP TutorialPHP image upload code (with the function of generating thumbnails and adding watermarks)_PHP tutorial

PHP image upload code (with the function of generating thumbnails and adding watermarks)_PHP tutorial

Jul 13, 2016 am 10:45 AM
phpuploadandcodeFunctionCanpictureIncreasepaymentwatermarksource codegenerate

This image upload source code can upload images and also has the function of generating thumbnails and adding watermarks to uploaded images. It can be said to be a perfect image uploader.

php tutorial image upload code (with the function of generating thumbnails and adding watermarks)
This image upload source code can upload images and also has the function of generating thumbnails and adding watermarks to uploaded images. It can be said to be a perfect image uploader.

class upfile {
public $filepath = "www.bKjia.c0m/"; //Folder to store uploaded files

public $filesize = 1000000; //Allow upload size

//If you want to modify the types of files allowed to be uploaded, please search [ switch ($upfiletype) { //File type ]

public $reimagesize = array (
true, //Whether to generate thumbnails
400, //Thumbnail width
300,//Thumbnail height
"" //Thumbnail storage folder. If empty, it is in the same directory as the current file to generate thumbnails. The file prefix is ​​r_
); //Whether to generate thumbnail array (generate or not, thumbnail width, thumbnail height, storage folder); Note: the storage folder is followed by '/'

public $india = true; //Whether to watermark true or false

public $indiaimage = ""; //If the watermark image address is empty, the image watermark will not be printed. If there is a text watermark, it is recommended not to enable the image watermark

public $indiaimagex = 100; //The distance between the image and the left side of the image

public $indiaimagey = 10; //The distance between the picture and the top of the picture

public $indiatext = "www.bKjia.c0m"; //Watermark text

public $fontsize = 6; //Watermark text size, 1 minimum and 6 maximum

public $indiatextx = 10; //The distance between the text and the left side of the image

public $indiatexty = 10; //The distance between the text and the top of the picture

public $r = 250; //Three primary colors of picture color $r red

public $g = 250; //$g green

public $b = 250; //$bblue

public $indiapath = ""; //The watermarked picture saving path, if it is empty, it will directly replace the original picture

 //开始上传处理
 function uploadfile($upfile) {
  if ($upfile == "") {
   die("uploadfile:参数不足");
  }
  if (!file_exists($this->filepath)) {
   mkdir($this->filepath);
  }
  $upfiletype = $upfile['type'];
  $upfilesize = $upfile['size'];
  $upfiletmpname = $upfile['tmp_name'];
  $upfilename = $upfile['name'];
  $upfileerror = $upfile['error'];
  if ($upfilesize > $this->filesize) {
   return false; //文件过大
  }
  switch ($upfiletype) { //文件类型
   case 'image/jpeg' :
    $type = 'jpg';
    break;
   case 'image/pjpeg' :
    $type = 'jpg';
    break;
   case 'image/png' :
    $type = 'png';
    break;
   case 'image/gif' :
    $type = 'gif';
    break;
  }
  if (!isset ($type)) {
   return false; //不支持此类型
  }
  if (!is_uploaded_file($upfiletmpname) or !is_file($upfiletmpname)) {
   return false;
   ; //文件不是经过正规上传的;
  }
  if ($this->upfileerror != 0) {
   return false; //其他错误
  }
  if ($this->upfileerror == 0) {
   if (!file_exists($upfiletmpname)) {
    return false; //临时文件不存在
   } else {
    $filename = date("ymdhis", time() + 3600 * 8); //图片已当前时间命名
    $filename = $this->filepath . $filename . "." . $type;
    if (!move_uploaded_file($upfiletmpname, $filename)) {
     return false; //文件在移动中丢失
    } else {
     if ($this->india == true) {
      $this->goindia($filename, $type,true);
     } else {
      if ($this->reimagesize[0] == true) {
       $this->goreimagesize($filename, $type);
      } else {
       return true; //上传成功!
       unlink($upfiletmpname);
      }
     }
    }

   }
  }

}
//Add watermark processing
function goindia($filename, $filetype,$reimage=false) {
if (!file_exists($filename)) {
$this->reerror(7); //The file to be watermarked does not exist
} else {
if ($filetype == "jpg") {
$im = imagecreatefromjpeg($filename);
} else
if ($filetype == "gif") {
       $im = imagecreatefromgif($filename);
} else
If ($filetype == "png") {
        $im = imagecreatefrompng($filename);
}
If ($this->indiatext != "") { //If the watermark text is not empty
$textcolor = imagecolorallocate($im, $this->r, $this->g, $this->b); //Set text color
Imagestring($im, $this->fontsize, $this->indiatextx, $this->indiatexty, $this->indiatext, $textcolor); //Write text into the image
}
if ($this->indiaimage != "") {//If the watermark image is not empty
$indiaimagetype = getimagesize($this->indiaimage);
$logow = $indiaimagetype[0]; //Get the width of the watermark image
$logoh = $indiaimagetype[1]; //Get the height of the watermark image
Switch ($indiaimagetype[2]) { //Determine the format of the watermark image
case 1 :
       $indiaimagetype = "gif";
$logo = imagecreatefromgif($this->indiaimage);
        break;
Case 2:
       $indiaimagetype = "jpg";
$logo = imagecreatefromjpeg($this->indiaimage);
        break;
Case 3:
       $indiaimagetype = "png";
$logo = imagecreatefrompng($this->indiaimage);
        break;
}
Imagealphablending($im, true); //Turn on color blending mode
Imagecopy($im, $logo, $this->indiaimagex, $this->indiaimagey, 0, 0, $logow, $logoh);
Imagedestroy($im);
Imagedestroy($logo);
}
}
if ($this->indiapath == "") { //If the watermark storage address is not empty
if ($filetype == "jpg") {
Imagejpeg($im, $filename);
} else
if ($filetype == "gif") {
Imagegif($im, $filename);
} else
If ($filetype == "png") {
Imagepng($im, $filename);
}
if($reimage == true){
$this->goreimagesize($filename,$filetype);
}else{
Return true; //Watermark added successfully
}
} else {
if (!file_exists($this->indiapath)) {
mkdir($this->indiapath);
Return false; //Please re-upload
} else {
$indianame = basename($filename);
$indianame = $this->indiapath . $indianame;
If ($filetype == "jpg") {
Imagejpeg($im, $indianame);
} else
If ($filetype == "gif") {
Imagegif($im, $indianame);
} else
If ($filetype == "png") {
Imagepng($im, $indianame);
}
If($reimage == true){
$this->goreimagesize($indianame,$filetype);
echo $indianame;
}else{
Return true; //Watermark added successfully
}
}
}
}
function goreimagesize($filename, $filetype) {
if (!file_exists($filename)) {
Return false; //The picture to be generated as a thumbnail does not exist
} else {
if ($filetype == 'jpg') {
$reimage = imagecreatefromjpeg($filename);
}
elseif ($filetype == 'png') {
$reimage = imagecreatefrompng($filename);
} else
if ($filetype == 'gif') {
$reimage = imagecreatefromgif($filename);
}
if (isset ($reimage)) {
$srcimagetype = getimagesize($filename);
$srcimagetypew = $srcimagetype[0]; //Get the original image width
$srcimagetypeh = $srcimagetype[1]; //Get the original image height
$reim = imagecreatetruecolor($this->reimagesize[1], $this->reimagesize[2]);
Imagecopyresized($reim, $reimage, 0, 0, 0, 0, $this->reimagesize[1], $this->reimagesize[2], $srcimagetypew, $srcimagetypeh);
$reimagepath = $this->reimagesize[3];
If ($reimagepath != "") { //If the watermark storage address is not empty
If (!file_exists($reimagepath)) {
         mkdir($reimagepath);
} else {
        $reimagename = basename($filename);
$reimagename = $reimagepath . "r_" . $reimagename;
If ($filetype == "gif")
Imagegif($reim, $reimagename);
       else
If ($filetype == "jpg")
Imagejpeg($reim, $reimagename);
       else
           if ($filetype == "png")
Imagepng($reim, $reimagename);
        return true;
}
} else {
$filename = basename($filename);
If($this->indiapath == ""){
$filename = $this->filepath."r_" . $filename;
      }else{
$filename = $this->indiapath."r_" . $filename;
}
If ($filetype == "gif")
Imagegif($reim, $filename);
      else
If ($filetype == "jpg")
Imagejpeg($reim, $filename);
       else
If ($filetype == "png")
Imagepng($reim, $filename);
Return true;
}

}
}
}

}
if ($_post["submit"]) {
$file = $_files['uploadfile'];
$upfile = new upfile();
echo $upfile->uploadfile($file);
}
?>





www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633045.htmlTechArticleThis image upload source code is a tool that can upload images and also has the ability to generate thumbnails and add images to uploaded images. With the watermark function, it can be said to be a perfect image uploader. PHP teaching...
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
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools