ASP.net image resizing

  • itHighway
  • Newbie
  • Newbie
  • itHighway
  • Posts: 7

Post 3+ Months Ago

Hello,

I am looking for asp.net script that can:

- Resize width and height of given image
- Save resized image to disk.
- The name of resized image should be [image name]_T.jpg


Please advice.


Thank you,
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • righteous_trespasser
  • Scuffle
  • Genius
  • User avatar
  • Posts: 6230
  • Loc: South-Africa

Post 3+ Months Ago

This is a page that does exactly that ... you can set the maximum image size (width and height) and then it saves both the original and the resized one on the server ...
Code: [ Select ]
<%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%>
<%@ Import Namespace=System.Drawing %>
<%@ Import Namespace=System.Drawing.Imaging %>
<%@ Import Namespace=System %>
<%@ Import Namespace=System.Web %>
<SCRIPT LANGUAGE="VBScript" runat="server">
    Const Lx = 173 ' max width for thumbnails
    Const Ly = 234 ' max height for thumbnails
    Const upload_dir = "images/" ' directory to upload file
    Const upload_original = "big" ' filename to save original as (suffix added by script)
    Const upload_thumb = "small" ' filename to save thumbnail as (suffix added by script)
    Const upload_max_size = 5000 ' max size of the upload (KB) note: this doesn't override any server upload limits
    Dim fileExt ' used to store the file extension (saves finding it mulitple times)
    Dim newWidth, newHeight As Integer ' new width/height for the thumbnail
    Dim l2 ' temp variable used when calculating new size
    Dim fileFld As HttpPostedFile ' used to grab the file upload from the form
    Dim originalimg As System.Drawing.Image ' used to hold the original image
    Dim msg ' display results
    Dim upload_ok As Boolean ' did the upload work ?
</script>


<%
    Randomize() ' used to help the cache-busting on the preview images
    upload_ok = False
    If LCase(Request.ServerVariables("REQUEST_METHOD")) = "post" Then
        fileFld = Request.Files(0) ' get the first file uploaded from the form (note:- you can use this to itterate through more than one image)
        If fileFld.ContentLength > upload_max_size * 1024 Then
            msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
        Else
            Try
                originalimg = System.Drawing.Image.FromStream(fileFld.InputStream)
                ' work out the width/height for the thumbnail. Preserve aspect ratio and honour max width/height
                ' Note: if the original is smaller than the thumbnail size it will be scaled up
                If (originalimg.Width / Lx) > (originalimg.Width / Ly) Then
                    l2 = originalimg.Width
                    newWidth = Lx
                    newHeight = originalimg.Height * (Lx / l2)
                    If newHeight > Ly Then
                        newWidth = newWidth * (Ly / newHeight)
                        newHeight = Ly
                    End If
                Else
                    l2 = originalimg.Height
                    newHeight = Ly
                    newWidth = originalimg.Width * (Ly / l2)
                    If newWidth > Lx Then
                        newHeight = newHeight * (Lx / newWidth)
                        newWidth = Lx
                    End If
                End If
                Dim thumb As New Bitmap(newWidth, newHeight)
                'Create a graphics object
                Dim gr_dest As Graphics = Graphics.FromImage(thumb)
                ' just in case it's a transparent GIF force the bg to white
                Dim sb = New SolidBrush(System.Drawing.Color.White)
                gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
                'Re-draw the image to the specified height and width
                gr_dest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height)
                Try
                    fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
                    originalimg.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt), originalimg.RawFormat)
                    thumb.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt), originalimg.RawFormat)
                    msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
                    upload_ok = True
                Catch ex As Exception
                    msg = "Sorry, there was a problem saving the image."
                End Try
                ' Housekeeping for the generated thumbnail
                If Not thumb Is Nothing Then
                    thumb.Dispose()
                    thumb = Nothing
                End If
            Catch
                msg = "Sorry, that was not an image we could process."
            End Try
        End If
        ' House Keeping !
        If Not originalimg Is Nothing Then
            originalimg.Dispose()
            originalimg = Nothing
        End If
    End If
%>
<html>
<head>
<title>ASP.NET File Upload and Resize Sample</title>
<META NAME="Description" CONTENT="ASP.NET File Upload and Resize Sample (Hybrid VB.NET)">
<META NAME="Keywords" CONTENT="ASP.NET, ASP, NET, VB, VBScript, Image, Upload, Resize, Thumbnail, Constrain, Filesize, File, Size, Free">
<META NAME="Copyright" CONTENT="Rufan-Redi Pty Ltd 2005">
<META NAME="Author" CONTENT="System developed by Jeremy at http://www.Rufan-Redi.com">
</head>
<body>

<p><b>Hybrid ASP.NET File Upload and Resize Sample (VB.NET)</b>
<br>Upload and resize a GIP/JPG/PNG images, ensuring filesizes are optimum.</p>

<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
<table>
<tr><td>Select the file to upload:</td><td><input type="file" name="upload_file"></td></tr>
    <tr>
        <td colspan="2" style="height: 19px">
            New FileName:
            <asp:TextBox ID="TextBoxFileName" runat="server"></asp:TextBox></td>
    </tr>
<tr><td colspan=2>Max upload size <%=upload_max_size%>Kb, gif/jpg/png only. The image will be saved as&nbsp; "New FileName-small" and
    "New FileName-big" accordingly. Just make sure that the original image is 260px
    x 351px big</td></tr>
<tr><td colspan=2><input type="submit" value="Upload" id="Submit1" language="javascript" onclick="return Submit1_onclick()">
</table>
</form>

<%
    If upload_ok Then
%>
<table>
<tr>
<td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt & "?" & rnd()%>"></td>
<td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt & "?" & rnd()%>"></td>
</tr>
</table>
<%
Else
    Response.Write(msg)
End If
%>
</body>
</html>
  1. <%@ Page Trace="False" Language="vb" aspcompat="false" debug="true" validateRequest="false"%>
  2. <%@ Import Namespace=System.Drawing %>
  3. <%@ Import Namespace=System.Drawing.Imaging %>
  4. <%@ Import Namespace=System %>
  5. <%@ Import Namespace=System.Web %>
  6. <SCRIPT LANGUAGE="VBScript" runat="server">
  7.     Const Lx = 173 ' max width for thumbnails
  8.     Const Ly = 234 ' max height for thumbnails
  9.     Const upload_dir = "images/" ' directory to upload file
  10.     Const upload_original = "big" ' filename to save original as (suffix added by script)
  11.     Const upload_thumb = "small" ' filename to save thumbnail as (suffix added by script)
  12.     Const upload_max_size = 5000 ' max size of the upload (KB) note: this doesn't override any server upload limits
  13.     Dim fileExt ' used to store the file extension (saves finding it mulitple times)
  14.     Dim newWidth, newHeight As Integer ' new width/height for the thumbnail
  15.     Dim l2 ' temp variable used when calculating new size
  16.     Dim fileFld As HttpPostedFile ' used to grab the file upload from the form
  17.     Dim originalimg As System.Drawing.Image ' used to hold the original image
  18.     Dim msg ' display results
  19.     Dim upload_ok As Boolean ' did the upload work ?
  20. </script>
  21. <%
  22.     Randomize() ' used to help the cache-busting on the preview images
  23.     upload_ok = False
  24.     If LCase(Request.ServerVariables("REQUEST_METHOD")) = "post" Then
  25.         fileFld = Request.Files(0) ' get the first file uploaded from the form (note:- you can use this to itterate through more than one image)
  26.         If fileFld.ContentLength > upload_max_size * 1024 Then
  27.             msg = "Sorry, the image must be less than " & upload_max_size & "Kb"
  28.         Else
  29.             Try
  30.                 originalimg = System.Drawing.Image.FromStream(fileFld.InputStream)
  31.                 ' work out the width/height for the thumbnail. Preserve aspect ratio and honour max width/height
  32.                 ' Note: if the original is smaller than the thumbnail size it will be scaled up
  33.                 If (originalimg.Width / Lx) > (originalimg.Width / Ly) Then
  34.                     l2 = originalimg.Width
  35.                     newWidth = Lx
  36.                     newHeight = originalimg.Height * (Lx / l2)
  37.                     If newHeight > Ly Then
  38.                         newWidth = newWidth * (Ly / newHeight)
  39.                         newHeight = Ly
  40.                     End If
  41.                 Else
  42.                     l2 = originalimg.Height
  43.                     newHeight = Ly
  44.                     newWidth = originalimg.Width * (Ly / l2)
  45.                     If newWidth > Lx Then
  46.                         newHeight = newHeight * (Lx / newWidth)
  47.                         newWidth = Lx
  48.                     End If
  49.                 End If
  50.                 Dim thumb As New Bitmap(newWidth, newHeight)
  51.                 'Create a graphics object
  52.                 Dim gr_dest As Graphics = Graphics.FromImage(thumb)
  53.                 ' just in case it's a transparent GIF force the bg to white
  54.                 Dim sb = New SolidBrush(System.Drawing.Color.White)
  55.                 gr_dest.FillRectangle(sb, 0, 0, thumb.Width, thumb.Height)
  56.                 'Re-draw the image to the specified height and width
  57.                 gr_dest.DrawImage(originalimg, 0, 0, thumb.Width, thumb.Height)
  58.                 Try
  59.                     fileExt = System.IO.Path.GetExtension(fileFld.FileName).ToLower()
  60.                     originalimg.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt), originalimg.RawFormat)
  61.                     thumb.Save(Server.MapPath(upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt), originalimg.RawFormat)
  62.                     msg = "Uploaded " & fileFld.FileName & " to " & Server.MapPath(upload_dir & upload_original & fileExt)
  63.                     upload_ok = True
  64.                 Catch ex As Exception
  65.                     msg = "Sorry, there was a problem saving the image."
  66.                 End Try
  67.                 ' Housekeeping for the generated thumbnail
  68.                 If Not thumb Is Nothing Then
  69.                     thumb.Dispose()
  70.                     thumb = Nothing
  71.                 End If
  72.             Catch
  73.                 msg = "Sorry, that was not an image we could process."
  74.             End Try
  75.         End If
  76.         ' House Keeping !
  77.         If Not originalimg Is Nothing Then
  78.             originalimg.Dispose()
  79.             originalimg = Nothing
  80.         End If
  81.     End If
  82. %>
  83. <html>
  84. <head>
  85. <title>ASP.NET File Upload and Resize Sample</title>
  86. <META NAME="Description" CONTENT="ASP.NET File Upload and Resize Sample (Hybrid VB.NET)">
  87. <META NAME="Keywords" CONTENT="ASP.NET, ASP, NET, VB, VBScript, Image, Upload, Resize, Thumbnail, Constrain, Filesize, File, Size, Free">
  88. <META NAME="Copyright" CONTENT="Rufan-Redi Pty Ltd 2005">
  89. <META NAME="Author" CONTENT="System developed by Jeremy at http://www.Rufan-Redi.com">
  90. </head>
  91. <body>
  92. <p><b>Hybrid ASP.NET File Upload and Resize Sample (VB.NET)</b>
  93. <br>Upload and resize a GIP/JPG/PNG images, ensuring filesizes are optimum.</p>
  94. <form id="Form1" enctype="multipart/form-data" method="post" runat="server">
  95. <table>
  96. <tr><td>Select the file to upload:</td><td><input type="file" name="upload_file"></td></tr>
  97.     <tr>
  98.         <td colspan="2" style="height: 19px">
  99.             New FileName:
  100.             <asp:TextBox ID="TextBoxFileName" runat="server"></asp:TextBox></td>
  101.     </tr>
  102. <tr><td colspan=2>Max upload size <%=upload_max_size%>Kb, gif/jpg/png only. The image will be saved as&nbsp; "New FileName-small" and
  103.     "New FileName-big" accordingly. Just make sure that the original image is 260px
  104.     x 351px big</td></tr>
  105. <tr><td colspan=2><input type="submit" value="Upload" id="Submit1" language="javascript" onclick="return Submit1_onclick()">
  106. </table>
  107. </form>
  108. <%
  109.     If upload_ok Then
  110. %>
  111. <table>
  112. <tr>
  113. <td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_original & fileExt & "?" & rnd()%>"></td>
  114. <td valign=top><img src="<%=upload_dir & TextBoxFileName.Text.ToString & "-" & upload_thumb & fileExt & "?" & rnd()%>"></td>
  115. </tr>
  116. </table>
  117. <%
  118. Else
  119.     Response.Write(msg)
  120. End If
  121. %>
  122. </body>
  123. </html>
  • rtorres
  • Born
  • Born
  • rtorres
  • Posts: 2

Post 3+ Months Ago

I realize this is a few years old but maybe someone can shed some light on this for me.

I have been looking for something like this for awhile. I tried this and get:
Quote:
The page cannot be displayed
The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.
--------------------------------------------------------------------------------

Please try the following:

Contact the Web site administrator if you believe that this request should be allowed.
Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.
HTTP Error 405 - The HTTP verb used to access this page is not allowed.
Internet Information Services (IIS)



I have tried setting the page to html, ASP, setting verbs in IIS for html, htm, asp with all access for each. I have set script and executable access, iis premissions wide open on image folder and virtual directory. I also tried to run root of website and also created virtual directory as well. What am I missing here?
  • nathanaeljones
  • Born
  • Born
  • nathanaeljones
  • Posts: 2

Post 3+ Months Ago

What version of IIS are you using? IIS7 has changed in regards to how verbs are permitted and denied.

I'd like to mention:

The snippet above is flawed, and will produce ugly results since it uses nearest-neighbor sampling instead of bicubic. Google "Image resizing pitfalls" for more info.

I'd suggest using something a little more mature, and well tested.

There is a 120kb drop-in library (at imageresizing .net) that lets you upload and resize images easily.

Here's an example that you can drop into any page with upload controls. It resizes all uploaded images to 1024x768 and converts them to jpegs.

You can also crop and resize to a ratio: using "width=1024&height=768&crop=auto" would automatically crop the edges to make the image fit the aspect ratio, then resize it to 1024x768.

You can rotate (&rotate=45), add padding, add watermarks, and do all kinds of cool stuff as well - it's extremely flexible.

Note that you can even resize after uploading with this module - just add ?width=400&height=300 in the URL of the <img src="" /> tag.

Code: [ Select ]
//Loop through each uploaded file
foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
  HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];

  //Get the physical path for the uploads folder
  string uploadFolder = MapPath("~/uploads");

  //Create the upload folder if it is missing
  if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);

  //The resizing settings can specify any of 30 commands.. See imageresizing .net for details.
  ResizeSettings resizeCropSettings = new ResizeSettings("maxwidth=1024&maxheight=768&format=jpg");

  //Generate a filename (GUIDs are safest).
  string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());

  //What final type of file will we have? This can depend on whether the resizeCropSettings sepcifies a format,
  // and what the original format was (if resizecropSettings doesn't specify one)
  fileName += "." + ImageBuilder.Current.EncoderProvider.GetEncoder(resizeCropSettings, fileUpload.PostedFile.FileName).Extension;

  //Resize the image
  ImageBuilder.Current.Build(file, fileName, resizeCropSettings);
}
  1. //Loop through each uploaded file
  2. foreach (string fileKey in HttpContext.Current.Request.Files.Keys) {
  3.   HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
  4.   //Get the physical path for the uploads folder
  5.   string uploadFolder = MapPath("~/uploads");
  6.   //Create the upload folder if it is missing
  7.   if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);
  8.   //The resizing settings can specify any of 30 commands.. See imageresizing .net for details.
  9.   ResizeSettings resizeCropSettings = new ResizeSettings("maxwidth=1024&maxheight=768&format=jpg");
  10.   //Generate a filename (GUIDs are safest).
  11.   string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());
  12.   //What final type of file will we have? This can depend on whether the resizeCropSettings sepcifies a format,
  13.   // and what the original format was (if resizecropSettings doesn't specify one)
  14.   fileName += "." + ImageBuilder.Current.EncoderProvider.GetEncoder(resizeCropSettings, fileUpload.PostedFile.FileName).Extension;
  15.   //Resize the image
  16.   ImageBuilder.Current.Build(file, fileName, resizeCropSettings);
  17. }
  • rtorres
  • Born
  • Born
  • rtorres
  • Posts: 2

Post 3+ Months Ago

Sorry for long delayed response. I am running IIS 6.0 on Win Server 2003 SP2
  • nathanaeljones
  • Born
  • Born
  • nathanaeljones
  • Posts: 2

Post 3+ Months Ago

rtorres wrote:
Sorry for long delayed response. I am running IIS 6.0 on Win Server 2003 SP2


In IIS6, you should be able to edit the extension mappings - make sure POST and GET are permitted.

Post Information

  • Total Posts in this topic: 6 posts
  • Users browsing this forum: No registered users and 55 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.