:
Click Browse and select an image. The image is displayed on the right.
Step 1:
Create CtFileUpLoad. ascx
Copy codeThe Code is as follows: <% @ Control Language = "C #" AutoEventWireup = "true" CodeFile = "CtFileUpLoad. ascx. cs"
Inherits = "WebParts_CtFileUpLoad" %>
<Table cellpadding = "0" cellspacing = "0">
<Tr>
<Td>
<Iframe src = "/WebParts/FileUpLoad. aspx? <% = ParsValue %> "width =" 240px "height =" 22px "frameborder =" 0 "scrolling =" no "> </iframe>
</Td>
<Td>
<Asp: TextBox runat = "server" ID = "tbFileName" style = "display: none"> </asp: TextBox>
<Div id = "dvImg" runat = "server" style = "position: absolute; margin-left: 50px;">
</Div>
</Td>
</Tr>
</Table>
<Script language = "javascript">
Function <% = ClientID %> CallLoaded ()
{
<% = OnLoaded %>;
}
</Script>
Copy codeThe Code is as follows: using System;
Using System. Collections;
Using System. Configuration;
Using System. Data;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. HtmlControls;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Drawing;
Public partial class WebParts_CtFileUpLoad: System. Web. UI. UserControl
{
Public bool AutoFileName
{
Get
{
Object ob = ViewState [ClientID + "AutoFileName"];
If (ob = null)
Ob = true;
Return (bool) ob;
}
Set
{
ViewState [ClientID + "AutoFileName"] = value;
}
}
Public string UpLoadPath
{
Get
{
Object ob = ViewState [ClientID + "UpLoadPath"];
If (ob = null)
Ob = "UPLOADFILES ";
Return ob. ToString ();
}
Set
{
ViewState [ClientID + "UpLoadPath"] = value;
}
}
Public string OnLoaded
{
Get
{
Object ob = ViewState [ClientID + "OnLoaded"];
If (ob = null)
Ob = "";
Return ob. ToString ();
}
Set
{
ViewState [ClientID + "OnLoaded"] = value;
}
}
Public string SupportExtension
{
Get
{
Object ob = ViewState [ClientID + "SupportExtension"];
If (ob = null)
{
Ob = "gif | png | jpeg | jpg ";
}
Return ob. ToString ();
}
Set
{
ViewState [ClientID + "SupportExtension"] = value. Replace (".","");
}
}
Public bool ShowImg
{
Get
{
Object ob = ViewState [ClientID + "ShowImg"];
If (ob = null)
Ob = true;
Return (bool) ob;
}
Set
{
If (bool) value)
DvImg. Style ["display"] = "block ";
Else
DvImg. Style ["display"] = "none ";
}
}
Public string FileName
{
Get
{
Return tbFileName. Text;
}
}
Protected string ParsValue = "";
Protected void Page_Load (object sender, EventArgs e)
{
ParsValue = "AutoFileName =" + AutoFileName. ToString () + "& SupportExtension =" + SupportExtension + "& UpLoadPath =" + UpLoadPath
+ "& ID =" + ClientID;
}
}
Step 2:
Create FileUpLoad. aspxCopy codeThe Code is as follows: <% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "FileUpLoad. aspx. cs" Inherits = "WebParts_FileUpLoad" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
</Head>
<Body style = "margin: 0px;">
<Form id = "form1" runat = "server">
<Div>
<Asp: FileUpload runat = "server" ID = "FileUpload1" onchange = "upload (this);"/>
<Asp: Button runat = "server" ID = "btUp" style = "display: none" OnClick = "btUp_Click"/>
</Div>
</Form>
</Body>
</Html>
<Script language = "javascript">
Function upload (ob)
{
Var expStr =/. * (<% = SupportExtension %>) $/I;
If (! ExpStr. test (ob. value ))
{
Alert ("the upload file type is incorrect. \ N (Supported file types: <% = SupportExtension %> )");
}
Else
{
Var btUp = document. getElementById ("<% = btUp. ClientID %> ");
BtUp. click ();
}
}
</Script>
Copy codeThe Code is as follows: using System;
Using System. Collections;
Using System. Configuration;
Using System. Data;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. HtmlControls;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Drawing;
Using System. IO;
Public partial class WebParts_FileUpLoad: System. Web. UI. Page
{
Protected string SupportExtension = "";
Protected string UpLoadPath = "";
Protected bool AutoFileName;
Protected string ParentID = "";
Protected void Page_Load (object sender, EventArgs e)
{
SupportExtension = Request. QueryString ["SupportExtension"];
UpLoadPath = Request. QueryString ["UpLoadPath"];
AutoFileName = bool. Parse (Request. QueryString ["AutoFileName"]. ToString ());
ParentID = Request. QueryString ["ID"]. ToString ();
}
Protected void btUp_Click (object sender, EventArgs e)
{
Boolean fileOK = false;
If (FileUpload1.HasFile)
{
String fileExtension =
System. IO. Path. GetExtension (FileUpload1.FileName). ToLower ();
String [] allowedExtensions = SupportExtension. Split (new string [] {"|"}, StringSplitOptions. RemoveEmptyEntries );
For (int I = 0; I <allowedExtensions. Length; I ++)
{
If (fileExtension = "." + allowedExtensions [I])
{
FileOK = true;
}
}
If (fileOK)
{
String path = "";
String name = "";
String sPath = "";
If (AutoFileName)
{
Name = DateTime. Now. Ticks. ToString () + System. IO. Path. GetExtension (FileUpload1.FileName). ToLower ();
}
Else
{
Name = FileUpload1.FileName;
}
SPath = Request. PhysicalApplicationPath + "\" + UpLoadPath + "\\";
Path = sPath + name; // image address
String fileName = name; // file name
String fileName_s = "s _" + name; // The name Of The thumbnail file.
Try
{
// FileInfo file = new FileInfo (name );
// String fileContentType = FileUpload1.PostedFile. ContentType;
// String name = FileUpload1.PostedFile. FileName; // client file path
// String fileName_sy = "sy _" + file. Name; // watermark image file Name (text)
// String fileName_syp = "syp _" + file. Name; // watermark image file Name (image)
// String webFilePath = Server. MapPath (UpLoadPath + "\" + fileName );
// String webFilePath_s = Server. MapPath (UpLoadPath + "\" + fileName_s );
String webFilePath = sPath + fileName; // server-side file path
String webFilePath_s = sPath + fileName_s; // server-side thumbnail path
If (! File. Exists (webFilePath ))
{
If (FileUpload1.PostedFile. ContentLength <2*1024*1024) // if the image is smaller than 2 MB
{
Try
{
FileUpload1.SaveAs (path); // use the saveAS method to save the file
System. Drawing. Image image = System. Drawing. Image. FromFile (path );
If (image. Width> 800 | image. Height> 600)
{
MakeThumbnail (webFilePath, webFilePath_s, 800,600, "W"); // method for generating thumbnails
}
Else
{
MakeThumbnail (webFilePath, webFilePath_s, 300,230, "W"); // method for generating thumbnails
}
Image. Dispose ();
// AddShuiYinWord (webFilePath, webFilePath_sy); // Save the watermark text image
// AddShuiYinPic (webFilePath, webFilePath_syp, webFilePath_sypf); // Save the image after adding the watermark image
// MakeThumbnail (webFilePath, webFilePath_s, 400,300, "W"); // method for generating thumbnails
Page. RegisterClientScriptBlock ("succcess", @ "<script>
Alert ('upload successful ');
Parent.doc ument. getElementById ('"+ ParentID +" _ "+" tbFileName "+ @"'). value = '"+ fileName_s + @"';
</Script> ");
}
Catch (Exception ex)
{
Page. registerClientScriptBlock ("err", "<script> alert ('prompt: File Upload Failed, cause of failure:" + ex. message + "'); </script> ");
}
}
Else
{
Page. RegisterClientScriptBlock ("err", "<script> alert ('note: The image size cannot exceed 2 MB '); </script> ");
}
}
Else
{
This. Page. RegisterClientScriptBlock ("err", "<script> alert ('image repeat'); </script> ");
}
}
Catch (System. Exception err)
{
This. Page. RegisterClientScriptBlock ("err", "<script> alert ('" + err. Message + "'); </script> ");
}
Try
{
Bitmap bmp = new Bitmap (path );
Int width = 0, height = 0;
Int dvalue = 200;
If (bmp. Width <dvalue & bmp. Height <200)
{
Width = bmp. Width;
Height = bmp. Height;
}
Else if (bmp. Width> bmp. Height)
{
Width = dvalue;
Height = dvalue * (bmp. Width/bmp. Height );
}
Else
{
Height = dvalue;
Width = dvalue * (bmp. Height/bmp. Width );
}
This. Page. RegisterClientScriptBlock ("show", @ "<script>
Parent. VarValue = '"+ UpLoadPath +"/"+ fileName_s +"'; "+
"Parent." + ParentID + "CallLoaded ();" +
"Parent.doc ument. getElementById ('" + ParentID + "_" + "dvImg" + @ "'). innerHTML =" +
"</Script> ");
Bmp. Dispose ();
}
Catch
{
}
Finally
{
// *** Determine whether the object exists. If so, delete the image.
If (File. Exists (path ))
{
// ***** Delete the image uploaded by the user client. Only the scaled image is saved on the server.
File. Delete (path );
}
}
}
Else
{
This. Page. RegisterClientScriptBlock ("err", "<script> alert ('error'); </script> ");
}
}
}
/// <Summary>
/// Generate a thumbnail
/// </Summary>
/// <Param name = "originalImagePath"> source image path (physical path) </param>
/// <Param name = "thumbnailPath"> thumbnail path (physical path) </param>
/// <Param name = "width"> thumbnail width </param>
/// <Param name = "height"> thumbnail height </param>
/// <Param name = "mode"> how to generate a thumbnail </param>
Public void MakeThumbnail (string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System. Drawing. Image originalImage = System. Drawing. Image. FromFile (originalImagePath );
Int towidth = width;
Int toheight = height;
Int x = 0;
Int y = 0;
Int ow = originalImage. Width;
Int oh = originalImage. Height;
Switch (mode)
{
Case "HW": // specify high-width Scaling (possibly deformed)
Break;
Case "W": // specify the width, and the height is proportional.
Toheight = originalImage. Height * width/originalImage. Width;
Break;
Case "H": // specify the height. The width is proportional.
Towidth = originalImage. Width * height/originalImage. Height;
Break;
Case "Cut": // specify the height and width (not deformed)
If (double) originalImage. Width/(double) originalImage. Height> (double) towidth/(double) toheight)
{
Oh = originalImage. Height;
Ow = originalImage. Height * towidth/toheight;
Y = 0;
X = (originalImage. Width-ow)/2;
}
Else
{
Ow = originalImage. Width;
Oh = originalImage. Width * height/towidth;
X = 0;
Y = (originalImage. Height-oh)/2;
}
Break;
Default:
Break;
}
// Create a bmp Image
System. Drawing. Image bitmap = new System. Drawing. Bitmap (towidth, toheight );
// Create a canvas
System. Drawing. Graphics g = System. Drawing. Graphics. FromImage (bitmap );
// Set a high quality Interpolation Method
G. InterpolationMode = System. Drawing. Drawing2D. InterpolationMode. High;
// Set high quality and smooth Low Speed
G. SmoothingMode = System. Drawing. Drawing2D. SmoothingMode. HighQuality;
// Clear the canvas and fill it with a transparent background color
G. Clear (System. Drawing. Color. Transparent );
// Draw the specified part of the original image at the specified position and in the specified size
G. DrawImage (originalImage, new System. Drawing. Rectangle (0, 0, towidth, toheight ),
New System. Drawing. Rectangle (x, y, ow, oh ),
System. Drawing. GraphicsUnit. Pixel );
Try
{
// Save the thumbnail in jpg format
Bitmap. Save (thumbnailPath, System. Drawing. Imaging. ImageFormat. Jpeg );
}
Catch (System. Exception e)
{
Throw e;
}
Finally
{
OriginalImage. Dispose ();
Bitmap. Dispose ();
G. Dispose ();
}
}
/// <Summary>
/// Add a text watermark to the image
/// </Summary>
/// <Param name = "Path"> original server image Path </param>
/// <Param name = "Path_sy"> generated image path with a text watermark </param>
Protected void AddShuiYinWord (string Path, string Path_sy)
{
String addText = "http://www.jb51.net ";
System. Drawing. Image image = System. Drawing. Image. FromFile (Path );
System. Drawing. Graphics g = System. Drawing. Graphics. FromImage (image );
G. DrawImage (image, 0, 0, image. Width, image. Height );
System. Drawing. Font f = new System. Drawing. Font ("Verdana", 16 );
System. Drawing. Brush B = new System. Drawing. SolidBrush (System. Drawing. Color. Blue );
G. DrawString (addText, f, B, 15, 15 );
G. Dispose ();
Image. Save (Path_sy );
Image. Dispose ();
}
/// <Summary>
/// Generate an image watermark on the Image
/// </Summary>
/// <Param name = "Path"> original server image Path </param>
/// <Param name = "Path_syp"> path of the image watermark generated </param>
/// <Param name = "Path_sypf"> watermark image path </param>
Protected void AddShuiYinPic (string Path, string Path_syp, string Path_sypf)
{
System. Drawing. Image image = System. Drawing. Image. FromFile (Path );
System. Drawing. Image copyImage = System. Drawing. Image. FromFile (Path_sypf );
System. Drawing. Graphics g = System. Drawing. Graphics. FromImage (image );
G. drawImage (copyImage, new System. drawing. rectangle (image. width-copyImage. width, image. height-copyImage. height, copyImage. width, copyImage. height), 0, 0, copyImage. width, copyImage. height, System. drawing. graphicsUnit. pixel );
G. Dispose ();
Image. Save (Path_syp );
Image. Dispose ();
}
}
Attribute:
SupportExtension: Custom upload format, separated by "|;
UpLoadPath: the folder for custom upload to the server;
AutoFileName ture indicates that the file name is automatically generated based on the time and will not be duplicated. false indicates that the original image name is overwritten.
Reprinted please indicate the source
18:39:27 by Qi xuejia