download code here!

Parameters:

  • File Types Accepted: GIF, PNG and JPG's Accepted
  • Current Save Path: D:\inetpub\goucham\tmp\
  • Images will be Saved As: JPG Format
  • Current Max Width: 550
  • Current Thumbnail Width: 75
  • Current Overlay Text: .NET Rules!!

  • Select File to Upload:




    
    <%@ Page Language="C#" EnableSessionState="False" EnableViewState="False"%>
    <%@ Import Namespace="System.IO"%>
    <%@ Import Namespace="System.Drawing"%>
    <%@ Import Namespace="System.Drawing.Imaging"%>
    <%@ Import Namespace="System.Text.RegularExpressions"%>
    <Script runat="server">
    /*
    Original concept and VB.Net code by Stephen Gilboy
    http://www.morningz.com/mz/crystal/dotnet/uploadImage.aspx
    
    C# Interpretation by Graham G. Elliott
    http://www.goucham.net/net/uploadImage.aspx
    
    sVirtualPath   -> Location of virtual path, used to later display
    sPath          -> Location of save path, make sure its a dir where ASPNET has FULL rights
    sOverlayText   -> Will be overlayed on top left of image, leave empty to not overlay
    iMaxWidth      -> Max width of the uploaded image, set to 0 to not resize
    iMaxThumbWidth -> Max width of generated thumbnail, set to 0 to not make thumbnail
    */
     const String sVirtualPath = "/tmp/";
     const String sOverlayText = ".NET Rules!!";
     const int iMaxWidth = 550;
     const int iMaxThumbWidth = 75;
     String sPath = HttpContext.Current.Server.MapPath(sVirtualPath);
    
     void Upload_Click(Object sender, EventArgs e)
     {
       if (uploadedFile.PostedFile != null) Process_Upload();
     }
    
     void Process_Upload()
     {
       try 
       {
        //Check for common errors.
         if (!Check_Upload(uploadedFile.PostedFile)) return;
    
        //Initializing local variables
         HttpPostedFile myUpload = uploadedFile.PostedFile;
         int myLength = myUpload.ContentLength;
         String myType = myUpload.ContentType;
         String myName = Path.GetFileName(myUpload.FileName);
    
         message.Text = "<b>Accepted Upload:</b> " + myName + "<br>" +
                        "<b>Content Type:</b> " + myType + "<br>" +
                        "<b>File Size:</b> " + myLength.ToString() + "<br>";
    
        //Running main image processing routine
         Process_Image(myUpload.InputStream, Path.ChangeExtension(myName, ".jpg"));
       }
       catch (Exception exc)
       {
         message.Text = "<b>Upload Failed:</b> " + exc.ToString();
       }
     }
     
     void Process_Image(Stream myStream, String myName)
     {
      //Initializing local variables
       System.Drawing.Image myImage = System.Drawing.Image.FromStream(myStream);
       String myPath = Path.Combine(sPath, myName);
       String myThumbPath = Path.Combine(sPath, "tn_" + myName);
       int oldWidth = myImage.Width;
       int oldHeight = myImage.Height;
       int newWidth;
       int newHeight;
    
       message.Text += "<b>Dimensions:</b> " + oldWidth + " x " + oldHeight + "<br>";
    
      //Determining new image size
       if ((iMaxWidth > 0) && (oldWidth > iMaxWidth))
       {
         newWidth = iMaxWidth;
         newHeight = (int) (oldHeight / ((Double) oldWidth / newWidth));
         message.Text += "<b>Image re-sized to:</b> " + newWidth + " x " + newHeight + "<br>";
       }else{
         newWidth = oldWidth;
         newHeight = oldHeight;
       }
    
      //Creating new, re-sized image
       Bitmap myBitmap = new Bitmap(myImage, newWidth, newHeight);
    
      //Creating the text overlay for re-sized image
       if (sOverlayText != "")
       {
         Graphics myCanvas = Graphics.FromImage(myBitmap);
         Font myFont = new Font("Verdana", 10, FontStyle.Bold);
         StringFormat myFormat = new StringFormat(StringFormatFlags.LineLimit);
    
         myCanvas.DrawString(sOverlayText, myFont, Brushes.Black, new PointF(4, 4), myFormat);
         myCanvas.DrawString(sOverlayText, myFont, Brushes.Black, new PointF(6, 6), myFormat);
         myCanvas.DrawString(sOverlayText, myFont, Brushes.Black, new PointF(4, 6), myFormat);
         myCanvas.DrawString(sOverlayText, myFont, Brushes.Black, new PointF(6, 4), myFormat);
         myCanvas.DrawString(sOverlayText, myFont, Brushes.Yellow, new PointF(5, 5), myFormat);
         myCanvas.Dispose();
    
         message.Text += "<b>Text Added:</b> " + sOverlayText + "<br>";
       }
    
      //Writing text overlayed image to disk and cleaning up
       myBitmap.Save(myPath, ImageFormat.Jpeg);
       myBitmap.Dispose();
    
       message.Text += "<b>File Saved As:</b> " + myPath + "<br>";
       image.Src = sVirtualPath + myName;
       image.Visible = true;
    
      //Creating thumbnail and writing to disk
       if (iMaxThumbWidth > 0)
       {
         Bitmap myThumb = new Bitmap(myImage, iMaxThumbWidth, (int) (newHeight / ((Double) newWidth / iMaxThumbWidth)));
         myThumb.Save(myThumbPath, ImageFormat.Jpeg);
         myThumb.Dispose();
    
         message.Text += "<b>Thumbnail Saved As:</b> " + myThumbPath + "<br>";
         thumb.Src = sVirtualPath + "tn_" + myName;
         thumb.Visible = true;
       }
    
      //Cleaning up parent image object
       myImage.Dispose();
     }
    
     bool Check_Upload(HttpPostedFile fileUpped)
     {
      //Checking to see if field was left empty
       if (fileUpped.FileName == "")
       {
         message.Text = "<b>Upload Failed:</b> No file sbumitted";
         return false;
       }
      //Checking for Jpeg / Gif mime types
       if (!Regex.IsMatch(fileUpped.ContentType, "image/(?:\\w?jpeg|gif|png)", RegexOptions.IgnoreCase))
       {
         message.Text = "<b>Upload Failed:</b> Only JPG's and GIF's allowed";
         return false;
       }
      //Checking for zero length.  You could also use to check for large files.
       if (fileUpped.ContentLength == 0)
       {
         message.Text = "<b>Upload Failed:</b> File cannot be zero bytes.";
         return false;
       }
    
       return true;
     }
    </Script>
    <html>
    <head>
    <title>Upload and Resize an Image</title>
    </head>
    <body bgcolor="white" style="font-family: Verdana; font-size: 8 pt;">
    <h2>Parameters:</h2>
    <li><b>File Types Accepted:</b> GIF, PNG and JPG's Accepted</li>
    <li><b>Current Save Path:</b> <%=sPath %></li>
    <li><b>Images will be Saved As:</b> JPG Format</li>
    <li><b>Current Max Width:</b> <%=iMaxWidth%></li>
    <li><b>Current Thumbnail Width:</b> <%=iMaxThumbWidth%></li>
    <li><b>Current Overlay Text:</b> <%=sOverlayText%></li>
    <br/>
    <form enctype="multipart/form-data" runat="server">
     Select File to Upload:
     <input id="uploadedFile" type="file" runat="server"/>
     <p><input id="upload" type="button" value="Upload" onserverclick="Upload_Click" runat="server"/></p>
     <p><asp:Label id="message" runat="server"/></p>
     <img id="image" visible="false" runat="server"/>
     <br>
     <img id="thumb" visible="false" runat="server"/>
    </form>
    </body>
    </html>