Php Image Upload code

Source: Internet
Author: User
Tags imagejpeg watermark images

Here is a simple example:
Copy codeThe 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 "<Script Language = 'javascript '> \ n history. back (); \ n alert ('$ this-> errormsg'); \ n </Script> \ 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
Copy codeThe Code is as follows:
<? Php
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;
$ 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. "/". $ 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. "/". $ this-> smallFolder. "/". $ newName) @ unlink ($ this-> 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. "/". $ this-> markFolder. "/". $ newName) @ unlink ($ this-> 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
Copy codeThe Code is as follows:
<? Php
$ 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 " <br> ";
Echo " <br> ";
Echo "<a href = './test. php'> continue upload </a> ";
} Else {
?>
<Form method = "post" action = "./test. php? Go = go "enctype =" multipart/form-data ">
<Input type = "file" name = "upfile"> <br>
<Input type = "submit" value = "Upload">
</Form>
<? Php
}
?>

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.