Php image upload class code _ php instance

Source: Internet
Author: User
Tags watermark images
Php image upload code provides comprehensive functions and can be selected as needed. Here is a simple example:

The code is as follows:


// Http://www.jb51.net
Class upLoad {
Public $ length; // specify the file size.
Public $ file; // determines whether this class is used for image upload or file upload.
Public $ fileName; // file name
Public $ fileTemp; // upload a temporary file
Public $ fileSize; // file size to be uploaded
Public $ error; // whether the file to be uploaded is wrong. php4 does not
Public $ fileType; // file Upload type
Public $ directory ;//
Public $ maxLen;
Public $ errormsg;
Function _ construct ($ length, $ file = true, $ directory)
{
$ This-> maxLen = $ length;
$ This-& gt; length = $ length * 1024;
$ This-> file = $ file; // true indicates the normal file, and false indicates the image judgment.
$ This-> directory = $ directory;
}
Public function upLoadFile ($ fileField)
{
$ This-> fileName = $ fileField ['name'];
$ This-> fileTemp = $ fileField ['tmp _ name'];
$ This-> error = $ fileField ['error'];
$ This-> fileType = $ fileField ['type'];
$ This-> fileSize = $ fileField ['size'];
$ PathSign = DIRECTORY_SEPARATOR ;///
If ($ this-> file) // upload a general file
{
$ Path = $ this-> _ isCreatedDir ($ this-> directory); // Obtain the path
If ($ path) // http://www.jb51.net
{
$ CreateFileType = $ this-> _ getFileType ($ this-> fileName); // you can specify a file category.
$ CreateFileName = uniqid (rand (); // randomly generate a file name
$ ThisDir = $ this-> directory. $ pathSign. $ createFileName. ".". $ createFileType;
If (@ move_uploaded_file ($ this-> fileTemp, $ thisDir) // Move the temporary file to the specified path
{
Return $ thisDir;
}
}
} Else {// image Upload
$ Path = $ this-> _ isCreatedDir ($ this-> directory); // Obtain the path
If ($ path) // path exists // http://www.jb51.net
{
$ CreateFileType = $ this-> _ getFileType ($ this-> fileName); // you can specify a file category.
$ CreateFileName = uniqid (rand ());
Return @ move_uploaded_file ($ this-> fileTemp, $ this-> directory. $ pathSign. $ createFileName. ".". $ createFileType )? True: false;
}
}
}
Public function _ isBig ($ length, $ fsize) // whether the returned file exceeds the specified size
{
Return $ fsize> $ length? True: false;
}
Public function _ getFileType ($ fileName) // Obtain the file suffix
{
Return end (explode (".", $ fileName ));
}
Public function _ isImg ($ fileType) // whether the image upload type is allowed
{
$ Type = array ("jpeg", "gif", "jpg", "bmp ");
$ FileType = strtolower ($ fileType );
$ FileArray = explode ("/", $ fileType );
$ File_type = end ($ fileArray );
Return in_array ($ file_type, $ type); // http://www.jb51.net
}
Public function _ isCreatedDir ($ path) // check whether the path exists. if it does not exist, create it.
{
If (! File_exists ($ path ))
{
Return @ mkdir ($ path, 0755 )? True: false; // permission 755 //
}
Else
{
Return true;
}
}
Public function showError () // Display error information
// Http://www.jb51.net
Echo "\ n ";
Exit ();
}
}
Class multiUpLoad extends upLoad {
Public $ FILES;
Function _ construct ($ arrayFiles, $ length, $ file = true, $ directory)
{
$ This-> FILES = $ arrayFiles;
Parent: :__ construct ($ length, $ file, $ directory );
}
Function upLoadMultiFile ()
{
$ Arr = array ();
If ($ this-> _ judge () | $ this-> _ judge () = "no") // if all files meet the specifications, start uploading.
{
Foreach ($ this-> FILES as $ key => $ value)
{
$ StrDir = parent: upLoadFile ($ this-> FILES [$ key]);
Array_push ($ arr, $ strDir );
}
// Http://www.jb51.net
Return $ arr;
} Else
{
Return false;
}
}
Function _ judge ()
{
If ($ this-> file)
{
Foreach ($ this-> FILES as $ key => $ value)
{
If ($ this-> _ isBig ($ this-> length, $ value ['size'])
{
$ This-> errormsg = "file exceeds $ this-> maxLen K ";
Parent: showError ();
}
If ($ value ['error'] = UPLOAD_ERR_NO_FILE)
{
// $ This-> errormsg = "an error occurred while uploading files ";
// Parent: showError ();
Return "no ";
}
}
Return true;
} Else
{
// Http://www.jb51.net
Foreach ($ this-> FILES as $ key => $ value)
{
If ($ this-> _ isBig ($ this-> length, $ value ['size'])
{
$ This-> errormsg = "Image exceeds $ this-> maxLen ";
Parent: showError ();
}
If ($ value ['error']! = 0)
{
$ This-> errormsg = "an error occurred while uploading images ";
Parent: showError ();
}
If (! $ This-> _ isImg ($ value ['type'])
{
$ This-> errormsg = "incorrect image format ";
Parent: showError ();
}
}
Return true;
}
}
}
?>


A more complex php Upload class that can automatically generate thumbnails
Step 1:
Create folders and layout:
Annex: Attachment (stores the uploaded original image in this directory)
|-Smallimg: stores Thumbnail slices.
|-Mark: stores watermark images.
Include: stores class files and fonts (the code used in this program is 04b_082.16.ttf)
|-Upfile. php: integrates simple upload to generate thumbnails and watermark class file information
|-04b_082.16.ttf: font file
Test. php: test file
Step 2 Upload class
Upfile. php

The code is as follows:


Class UPImages {
Var $ attachment folder = "annex"; // The Attachment storage point. The default value is annex.
Var $ smallFolder = "smallimg"; // path for storing thumbnails. note: the path must be a subdirectory under $ Alibaba folder. the default value is smallimg.
Var $ markFolder = "mark"; // watermark image storage location
Var $ upFileType = "jpg gif png"; // The Upload type. default value: jpg gif png rar zip
Var $ upFileMax = 1024; // The maximum upload size. the unit is "KB". The default value is KB.
Var $ fontType; // font
Var $ maxWidth = 500; // maximum image width
Var $ maxHeight = 600; // maximum image height
Function UPImages ($ inclufolder, $ smallFolder, $ includeFolder ){
$ This-> Folder folder = $ folder;
$ This-> smallFolder = $ smallFolder;
$ This-> fontType = $ includeFolder. "/04b_082.16.ttf ";
}
Function upLoad ($ inputName ){
$ ImageName = time (); // set the current time to the image name
If (@ empty ($ _ FILES [$ inputName] ["name"]) die (error ("No image information is uploaded, please confirm "));
$ Name = explode (".", $ _ FILES [$ inputName] ["name"]); // separate the FILES before Upload with "." to obtain the file type
$ ImgCount = count ($ name); // Obtain the number of interceptions.
$ ImgType = $ name [$ imgCount-1]; // type of the retrieved file
If (strpos ($ this-> upFileType, $ imgType) === false) die (error ("only supported file Upload types ". $ this-> upFileType. "not supported ". $ imgType ));
$ Photo = $ imageName. ".". $ imgType; // name of the file written to the database
$ UploadFile = $ this-> Folder folder. "/". $ photo; // name of the uploaded file
$ UpFileok = move_uploaded_file ($ _ FILES [$ inputName] ["tmp_name"], $ uploadFile );
If ($ upFileok ){
$ ImgSize = $ _ FILES [$ inputName] ["size"];
$ KSize = round ($ imgSize/1024 );
If ($ kSize> ($ this-> upFileMax * 1024 )){
@ Unlink ($ uploadFile );
Die (error ("uploaded file exceeds". $ this-> upFileMax. "KB "));
}
} Else {
Die (error ("failed to upload the image, please make sure that your Upload file does not exceed $ upFileMax KB or the upload time has timed out "));
}
Return $ photo;
}
Function getInfo ($ photo ){
$ Photo = $ this-> specify folder. "/". $ photo;
$ ImageInfo = getimagesize ($ photo );
$ ImgInfo ["width"] = $ imageInfo [0];
$ ImgInfo ["height"] = $ imageInfo [1];
$ ImgInfo ["type"] = $ imageInfo [2];
$ ImgInfo ["name"] = basename ($ photo );
Return $ imgInfo;
}
Function smallImg ($ photo, $ width = 128, $ height = 128 ){
$ ImgInfo = $ this-> getInfo ($ photo );
$ Photo = $ this-> Getting folder. "/". $ photo; // Obtain the image source
$ NewName = substr ($ imgInfo ["name"], 0, strrpos ($ imgInfo ["name"], "."). "_thumb.jpg"; // New image name
If ($ imgInfo ["type"] = 1 ){
$ Img = imagecreatefromgif ($ photo );
} Elseif ($ imgInfo ["type"] = 2 ){
$ Img = imagecreatefromjpeg ($ photo );
} Elseif ($ imgInfo ["type"] = 3 ){
$ Img = imagecreatefrompng ($ photo );
} Else {
$ Img = "";
}
If (empty ($ img) return False;
$ Width = ($ width> $ imgInfo ["width"])? $ ImgInfo ["width"]: $ width;
$ Height = ($ height> $ imgInfo ["height"])? $ ImgInfo ["height"]: $ height;
$ SrcW = $ imgInfo ["width"];
$ SrcH = $ imgInfo ["height"];
If ($ srcW * $ width> $ srcH * $ height ){
$ Height = round ($ srcH * $ width/$ srcW );
} Else {
$ Width = round ($ srcW * $ height/$ srcH );
}
If (function_exists ("imagecreatetruecolor ")){
$ NewImg = imagecreatetruecolor ($ width, $ height );
ImageCopyResampled ($ newImg, $ img, 0, 0, 0, $ width, $ height, $ imgInfo ["width"], $ imgInfo ["height"]);
} Else {
$ NewImg = imagecreate ($ width, $ height );
ImageCopyResized ($ newImg, $ img, 0, 0, 0, $ width, $ height, $ imgInfo ["width"], $ imgInfo ["height"]);
}
If ($ this-> toFile ){
If (file_exists ($ this-> Folder folder. "/". $ this-> smallFolder. "/". $ newName) @ unlink ($ this-> Folder folder. "/". $ this-> smallFolder. "/". $ newName );
ImageJPEG ($ newImg, $ this-> exist folder. "/". $ this-> smallFolder. "/". $ newName );
Return $ this-> revoke folder. "/". $ this-> smallFolder. "/". $ newName;
} Else {
ImageJPEG ($ newImg );
}
ImageDestroy ($ newImg );
ImageDestroy ($ img );
Return $ newName;
}
Function waterMark ($ photo, $ text ){
$ ImgInfo = $ this-> getInfo ($ photo );
$ Photo = $ this-> specify folder. "/". $ photo;
$ NewName = substr ($ imgInfo ["name"], 0, strrpos ($ imgInfo ["name"], "."). "_mark.jpg ";
Switch ($ imgInfo ["type"]) {
Case 1:
$ Img = imagecreatefromgif ($ photo );
Break;
Case 2:
$ Img = imagecreatefromjpeg ($ photo );
Break;
Case 3:
$ Img = imagecreatefrompng ($ photo );
Break;
Default:
Return False;
}
If (empty ($ img) return False;
$ Width = ($ this-> maxWidth> $ imgInfo ["width"])? $ ImgInfo ["width"]: $ this-> maxWidth;
$ Height = ($ this-> maxHeight> $ imgInfo ["height"])? $ ImgInfo ["height"]: $ this-> maxHeight;
$ SrcW = $ imgInfo ["width"];
$ SrcH = $ imgInfo ["height"];
If ($ srcW * $ width> $ srcH * $ height ){
$ Height = round ($ srcH * $ width/$ srcW );
} Else {
$ Width = round ($ srcW * $ height/$ srcH );
}
If (function_exists ("imagecreatetruecolor ")){
$ NewImg = imagecreatetruecolor ($ width, $ height );
ImageCopyResampled ($ newImg, $ img, 0, 0, 0, $ width, $ height, $ imgInfo ["width"], $ imgInfo ["height"]);
} Else {
$ NewImg = imagecreate ($ width, $ height );
ImageCopyResized ($ newImg, $ img, 0, 0, 0, $ width, $ height, $ imgInfo ["width"], $ imgInfo ["height"]);
}
$ White = imageColorAllocate ($ newImg, 255,255,255 );
$ Black = imageColorAllocate ($ newImg, 0, 0, 0 );
$ Alpha = imageColorAllocateAlpha ($ newImg, 230,230,230, 40 );
ImageFilledRectangle ($ newImg, 0, $ height-26, $ width, $ height, $ alpha );
ImageFilledRectangle ($ newImg, 13, $ height-20, 15, $ height-7, $ black );
ImageTTFText ($ newImg, 4.9, 0, 20, $ height-14, $ black, $ this-> fontType, $ text [0]);
ImageTTFText ($ newImg, 4.9, 0, 20, $ height-6, $ black, $ this-> fontType, $ text [1]);
If ($ this-> toFile ){
If (file_exists ($ this-> Folder folder. "/". $ this-> markFolder. "/". $ newName) @ unlink ($ this-> Folder folder. "/". $ this-> markFolder. "/". $ newName );
ImageJPEG ($ newImg, $ this-> composer folder. "/". $ this-> markFolder. "/". $ newName );
Return $ this-> exist folder. "/". $ this-> markFolder. "/". $ newName;
} Else {
ImageJPEG ($ newImg );
}
ImageDestroy ($ newImg );
ImageDestroy ($ img );
Return $ newName;
}
}
?>


Step 3: Test the upload class
Test. php

The code is as follows:


$ Export folder = "annex ";
$ SmallFolder = "smallimg ";
$ MarkFolder = "mark ";
$ IncludeFolder = "include ";
Require ("./". $ includeFolder. "/upfile. php ");
$ Img = new UPImages ($ inclufolder, $ smallFolder, $ includeFolder );
$ Text = array ("www.jb51.net", "all rights reserved ");
If (@ $ _ GET ["go"]) {
$ Photo = $ img-> upLoad ("upfile ");
$ Img-> maxWidth = $ img-> maxHeight = 350; // Set the watermark image value.
$ Img-> toFile = true;
$ NewSmallImg = $ img-> smallImg ($ photo );
$ NewMark = $ img-> waterMark ($ photo, $ text );
Echo"

";
Echo"

";
Echo "continue Upload ";
} Else {
?>

}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.