Source code of a class library Uploaded By. Net images

Source: Internet
Author: User

Uploading images to the server is a frequently used function in website development. Its implementation is also very simple. You can create an upload class UpLoadAndSaveImage, which contains three functions: UpLoadAndSave, CreateFilePath, and SaveToServer. You can call the following UpLoadAndSave function for use. The first parameter of this function is the image data to be uploaded, and the second parameter is the uploaded virtual path (relative path ), the third parameter is the format of the uploaded image, and the fourth parameter is the physical path of the uploaded image. Call the CreateFilePath function in this function to generate a random image name, and then call SaveToServer to save the image to the server.
Public string UpLoadAndSave (byte [] data, refstring virPath, string fext, string physicPath)
{
// Return the physical address of the file and modify the virtual address
If (data = null | virPath = null | fext = null | physicPath = "")
{
Throw new Exception ("invalid parameter ");
}
String rtnValue = SaveToServer (data, fext, physicPath, data. Length );
VirPath + = rtnValue;
PhysicPath + = rtnValue;
Return physicPath;
}
Private string CreateFilePath (string fext)
{
String filePath = "";
Random rd = new Random ();
FilePath + = DateTime. Now. Year. ToString ("0000 ");
FilePath + = DateTime. Now. Month. ToString ("00 ");
FilePath + = DateTime. Now. Date. ToString ("00 ");
FilePath + = DateTime. Now. Hour. ToString ("00 ");
FilePath + = DateTime. Now. Minute. ToString ("00 ");
FilePath + = DateTime. Now. Second. ToString ("00 ");
FilePath + = DateTime. Now. Millisecond. ToString ("00 ");
FilePath + = rd. Next (99). ToString ("00 ");
FilePath + = "." + fext;
Return filePath;
}
Private string SaveToServer (byte [] data, string fext, string physicPath, int fileLen)
{
String filePath = CreateFilePath (fext );
String rtnValue = filePath;
FilePath = filePath. Insert (0, @ physicPath );
If (File. Exists (filePath ))
{
FilePath = CreateFilePath (fext );
RtnValue = filePath;
}
FileStream fs = new FileStream (filePath, FileMode. CreateNew );
Fs. Write (data, 0, fileLen );
Fs. Close ();
Return rtnValue;
}

// Call this upload class on other pages. See the following example:
UpLoadAndSaveImage upload = new UpLoadAndSaveImage ();
Try
{
String virPath = "UploadFiles /";
String physicPath = Server. MapPath (Request. ApplicationPath + "/" + "UploadFiles /");
String fext = this. File1.PostedFile. FileName;
If (fext. Length = 0)
{
Return;
}

Fext = Path. GetExtension (fext). ToLower ();
If (fext! = ". Jpg" & fext! = ". Gif" & fext! = ". Bmp" & fext! = ". Doc" & fext! = ". Rar" & fext! = ". Zip" & fext! = ". Jpeg ")
{
Response. Write ("<script> alert ('invalid file format, the file format must be jpg or jpeg or gif
Or bmp or doc or rar or zip ') </script> ");
Return;
}

Byte [] data = newbyte [this. File1.PostedFile. ContentLength];

This. File1.PostedFile. InputStream. Read (data, 0, this. File1.PostedFile. ContentLength );

PhysicPath = upload. UpLoadAndSave (data, ref virPath, fext, physicPath );

Url = virPath;

If (Session ["PhotoUrl"] = null)
{
ArrayList al = new ArrayList ();
Al. Add (physicPath );
Session ["PhotoUrl"] = al;
}
Else
{
ArrayList Al = (ArrayList) Session ["PhotoUrl"];

Al2.Add (physicPath );

Session ["PhotoUrl"] = Al;
}
}
Catch (Exception ex)
{
Response. Write ("<script> alert ('" + ex. Message + "'); </script> ");
}

// If You Want To specify the size of the uploaded image, it can be generated before calling this upload class. See the following example:

Try
{
EmpPic = new Bitmap (File1.PostedFile. InputStream );
}
Catch
{
Script. Alert ("incorrect image format! ");
Return false;
}
Bitmap picSmall = new Bitmap (empPic, 227,91); // generate the image size
MemoryStream stream = new MemoryStream ();

PicSmall. Save (stream, ImageFormat. Jpeg );
Byte [] byteArray = stream. ToArray ();
PathName1 = "Photo /";
PathName = Server. MapPath (Request. ApplicationPath + "/Photo /");
UpLoadAndSaveImage upimage = new UpLoadAndSaveImage ();
PathName = upimage. UpLoadAndSave (byteArray, ref PathName1, ". jpg", PathName );

The following is an Image Upload class I have written with the watermark function:

// Generate a thumbnail.
Using System;
Using System. IO;
Using System. Web;
Using System. Web. UI. HtmlControls;
Using System. Drawing;
Namespace myuplevels
{
/// <Summary>
/// Non-cold upload class (image ). Author: Non-cold. function: File Upload (mainly used for image uploading );
/// </Summary>
Public class Upload
{
Private int _ Error = 0; // the upload status is returned.
Private int _ MaxSize = 5120000; // maximum size of a single uploaded file (default)
Private string _ FileType = "jpg/gif/bmp/png"; // The supported upload types are separated "/"
Private string _ SavePath = System. Web. HttpContext. Current. Server. MapPath (".") + "\"; // Save the actual path of the file
Private int _ SaveType = 0; // type of the file to be uploaded. 0 indicates that the file name is automatically generated.
Private HtmlInputFile _ FormFile; // upload control.
Private string _ InFileName = ""; // the file name setting is not automatically generated.
Private string _ OutFileName = ""; // output file name.
Private bool _ IsCreateImg = true; // whether to generate a thumbnail.
Private bool _ Iss = false; // whether a thumbnail is generated.
Private int _ Height = 0; // obtain the Height of the uploaded Image
Private int _ Width = 0; // obtain the Width of the uploaded Image
Private int _ sHeight = 120; // you can specify the height of the generated thumbnail.
Private int _ sWidth = 120; // you can specify the width of the generated thumbnail.
Private bool _ IsDraw = false; // you can specify whether to add a watermark.
Private int _ DrawStyle = 0; // set the watermark mode to 0: Text watermark mode, 1: Image Watermark mode, 2: Not added
Private int _ DrawString_x = 10; // draw the X coordinate of the text (upper left corner)
Private int _ DrawString_y = 10; // draw the Y coordinate of the text (upper left corner)
Private string _ AddText = "Hangzhou five-dimensional multimedia \ nHTTP: // WWW.5D. CN"; // sets the watermark content
Private string _ Font = ""; // set the watermark Font
Private int _ FontSize = 12; // set the watermark size
Private int _ FileSize = 0; // obtain the size of the uploaded file
Private string _ CopyIamgePath = System. web. httpContext. current. server. mapPath (". ") +"/images/5dm_new.jpg "; // the actual address of the covered image in the image watermark Mode

/// <Summary>
/// Error returned value. 1. No uploaded file exists. 2. the type is not allowed. 3. The size exceeds the limit. 4. Unknown error. 0. The upload is successful.
/// </Summary>
Public int Error
{
Get {return _ Error ;}
}
/// <Summary>
/// Maximum size of a single object to be uploaded
/// </Summary>
Public int MaxSize
{
Set {_ MaxSize = value ;}
}
/// <Summary>
/// The supported upload types are separated "/"
/// </Summary>
Public string FileType
{
Set {_ FileType = value ;}
}
/// <Summary>
///// Actual path for saving the file
/// </Summary>
Public string SavePath
{
Set {_ SavePath = System. Web. HttpContext. Current. Server. MapPath (value );}
Get {return _ SavePath ;}
}
/// <Summary>
/// Type of the uploaded file. 0 indicates that the file name is automatically generated.
/// </Summary>
Public int SaveType
{
Set {_ SaveType = value ;}
}
/// <Summary>
/// Upload Control
/// </Summary>
Public HtmlInputFile FormFile
{
Set {_ FormFile = value ;}
}
/// <Summary>
///// The file name setting is not automatically generated.
/// </Summary>
Public string InFileName
{
Set {_ InFileName = value ;}
}
/// <Summary>
/// Output file name
/// </Summary>
Public string OutFileName
{
Get {return _ OutFileName ;}
Set {_ OutFileName = value ;}
}
/// <Summary>
/// Whether a thumbnail is generated.
/// </Summary>
Public bool Iss
{
Get {return _ Iss ;}
}
/// <Summary>
///// Obtain the width of the uploaded Image
/// </Summary>
Public int Width
{
Get {return _ Width ;}
}
/// <Summary>
//// Obtain the height of the uploaded Image
/// </Summary>
Public int Height
{
Get {return _ Height ;}
}
/// <Summary>
/// Set the width of the thumbnail
/// </Summary>
Public int sWidth
{
Get {return _ sWidth ;}
Set {_ sWidth = value ;}
}
/// <Summary>
/// Set the height of the thumbnail
/// </Summary>
Public int sHeight
{
Get {return _ sHeight ;}
Set {_ sHeight = value ;}
}
/// <Summary>
/// Whether to generate a thumbnail
/// </Summary>
Public bool IsCreateImg
{
Get {return _ IsCreateImg ;}
Set {_ IsCreateImg = value ;}
}
/// <Summary>
/// Whether to add a watermark
/// </Summary>
Public bool IsDraw
{
Get {return _ IsDraw ;}
Set {_ IsDraw = value ;}
}
/// <Summary>
/// Set the watermark mode. The value 0 indicates the text watermark mode, the value 1 indicates the image watermark mode, and the value 2 indicates the text watermark mode.
/// </Summary>
Public int DrawStyle
{
Get {return _ DrawStyle ;}
Set {_ DrawStyle = value ;}
}
/// <Summary>
/// Draw the X coordinate of the text (upper left corner)
/// </Summary>
Public int DrawString_x
{
Get {return _ DrawString_x ;}
Set {_ DrawString_x = value ;}
}
/// <Summary>
/// Plot the Y coordinate of the text (upper left corner)
/// </Summary>
Public int DrawString_y
{
Get {return _ DrawString_y ;}
Set {_ DrawString_y = value ;}
}
/// <Summary>
/// Set the text watermark content
/// </Summary>
Public string AddText
{
Get {return _ AddText ;}
Set {_ AddText = value ;}
}
/// <Summary>
/// Set the text watermark font
/// </Summary>
Public string Font
{
Get {return _ Font ;}
Set {_ Font = value ;}
}
/// <Summary>
/// Set the text watermark size
/// </Summary>
Public int FontSize
{
Get {return _ FontSize ;}
Set {_ FontSize = value ;}
}
Public int FileSize
{
Get {return _ FileSize ;}
Set {_ FileSize = value ;}
}
/// <Summary>
/// Actual address of the covered image in the image watermark Mode
/// </Summary>
Public string CopyIamgePath
{
Set {_ CopyIamgePath = System. Web. HttpContext. Current. Server. MapPath (value );}
}

// Get the file suffix
Private string GetExt (string path)
{
Return Path. GetExtension (path );
}
// Obtain the name of the output file.
Private string FileName (string Ext)
{
If (_ SaveType = 0 | _ InFileName. Trim () = "")
Return DateTime. Now. ToString ("yyyyMMddHHmmssfff") + Ext;
Else
Return _ InFileName;
}
// Check the type of the uploaded file and whether upload is allowed.
Private bool IsUpload (string Ext)
{
Ext = Ext. Replace (".","");
Bool B = false;
String [] arrFileType = _ FileType. Split (';');
Foreach (string str in arrFileType)
{
If (str. ToLower () = Ext. ToLower ())
{
B = true;
Break;
}
}
Return B;
}
// Upload the main part.
Public void Open ()
{
HttpPostedFile hpFile = _ FormFile. PostedFile;
If (hpFile = null | hpFile. FileName. Trim () = "")
{
_ Error = 1;
Return;
}

String Ext = GetExt (hpFile. FileName );
If (! IsUpload (Ext ))
{
_ Error = 2;
Return;
}

Int iLen = hpFile. ContentLength;
If (iLen> _ MaxSize)
{
_ Error = 3;
Return;
}

Try
{

If (! Directory. Exists (_ SavePath ))
Directory. CreateDirectory (_ SavePath );
Byte [] bData = new byte [iLen];
HpFile. InputStream. Read (bData, 0, iLen );
String FName;
FName = FileName (Ext );
String TempFile = "";
If (_ IsDraw)
{
TempFile = FName. split ('. '). getValue (0 ). toString () + "_ temp. "+ FName. split ('. '). getValue (1 ). toString ();
}
Else
{
TempFile = FName;
}
FileStream newFile = new FileStream (_ SavePath + TempFile, FileMode. Create );
NewFile. Write (bData, 0, bData. Length );
NewFile. Flush ();
Int _ FileSizeTemp = hpFile. ContentLength;

If (_ IsDraw)
{
If (_ DrawStyle = 0)
{
System. Drawing. Image Img1 = System. Drawing. Image. FromStream (newFile );
Graphics g = Graphics. FromImage (Img1 );
G. DrawImage (Img1, 100,100, Img1.Width, Img1.Height );
Font f = new Font (_ Font, _ FontSize );
Brush B = new SolidBrush (Color. Red );
String addtext = _ AddText;
G. DrawString (addtext, f, B, _ DrawString_x, _ DrawString_y );
G. Dispose ();
Img1.Save (_ SavePath + FName );
Img1.Dispose ();

}
Else
{
System. Drawing. Image image = System. Drawing. Image. FromStream (newFile );
System. Drawing. Image copyImage = System. Drawing. Image. FromFile (_ CopyIamgePath );
Graphics g = Graphics. FromImage (image );
G. drawImage (copyImage, new Rectangle (image. width-copyImage. width-5, image. height-copyImage. height-5, copyImage. width, copyImage. height), 0, 0, copyImage. width, copyImage. height, GraphicsUnit. pixel );
G. Dispose ();
Image. Save (_ SavePath + FName );
Image. Dispose ();
}
}

Try
{
// Obtain the image height and width
System. Drawing. Image Img = System. Drawing. Image. FromStream (newFile );
_ Width = Img. Width;
_ Height = Img. Height;
// Generate the thumbnail part
If (_ IsCreateImg)
{
// If the size of the uploaded file is less than 15 kb, no thumbnails are generated.
If (ilen> 15360)
{

System. Drawing. Image newImg = Img. GetThumbnailImage (_ sWidth, _ sHeight, null, System. IntPtr. Zero );
NewImg. save (_ SavePath + FName. split ('. '). getValue (0 ). toString () + "_ s. "+ FName. split ('. '). getValue (1 ). toString ());
NewImg. Dispose ();
_ Iss = true;
}
}
If (_ IsDraw)
{
If (File. exists (_ SavePath + FName. split ('. '). getValue (0 ). toString () + "_ temp. "+ FName. split ('. '). getValue (1 ). toString ()))
{
NewFile. Dispose ();
File. delete (_ SavePath + FName. split ('. '). getValue (0 ). toString () + "_ temp. "+ FName. split ('. '). getValue (1 ). toString ());
}
}
}
Catch {}
NewFile. Close ();
NewFile. Dispose ();
_ OutFileName = FName;
_ FileSize = _ FileSizeTemp;
_ Error = 0;
Return;
}
Catch
{
_ Error = 4;
Return;
}
}
}
}

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.