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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.