locked
upload and resize multiple files RRS feed

  • Question

  • User-1937266229 posted

     Hey Guys

    I have some code that i am using to upload multiple images but i would like the images to be resized on upload.

    could anyone be kind enough to give me an example of how this can be implemented ?

    I am sorry if this had been asked 10000 times and i have searched for the past 2 days trying to find an answer with no luck :(

    Here is my code and i would be very greatfull if anyone can help.

    Cheers

    Andy

     

    <script language="vb" runat="server">
    Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs)

       Dim filepath As String = Server.MapPath(".") & "/Images/"
       Dim uploadedFiles As HttpFileCollection = Request.Files
       Dim i As Integer = 0

       Do Until i = uploadedFiles.Count
         Dim userPostedFile As HttpPostedFile = uploadedFiles(i)

         Try
            If (userPostedFile.ContentLength > 0) Then
               Label1.Text += "<u>File #" & (i + 1) & "</u><br>"
               Label1.Text += "File Content Type: " & _
                  userPostedFile.ContentType & "<br>"
               Label1.Text += "File Size: " & _
                  userPostedFile.ContentLength & "kb<br>"
               Label1.Text += "File Name: " & _
                  userPostedFile.FileName & "<br>"

               'random name
               Dim timestamp = year(now) & right("0" & month(now),2) & right("0" & day(now),2) & right("0" & hour(now),2) & right("0" & minute(now),2) & right("0" & second(now),2)

               userPostedFile.SaveAs(filepath & "\" & _
                  System.IO.Path.GetFileName(timestamp & "-" & userPostedFile.FileName))

               Label1.Text += "Location where saved: " & _
                  filepath & "\" & _
                  System.IO.Path.GetFileName(userPostedFile.FileName) & _
                  "<p>"
            End If
         Catch ex As Exception
            Label1.Text += "Error:<br>" & ex.Message
         End Try
         i += 1
       Loop
    End Sub
    </script>

     

     

     

    Friday, January 30, 2009 7:46 PM

Answers

  • User-1682931557 posted
    Hi,

    Pls see -- Dynamically resize uploaded images (in C#):
    http://www.codeproject.com/KB/web-image/pnguploader.aspx

    VB.Net sample is here:
    http://www.codeproject.com/KB/graphics/image_croppingVBNet.aspx
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 31, 2009 4:22 AM

All replies

  • User-1682931557 posted
    Hi,

    Pls see -- Dynamically resize uploaded images (in C#):
    http://www.codeproject.com/KB/web-image/pnguploader.aspx

    VB.Net sample is here:
    http://www.codeproject.com/KB/graphics/image_croppingVBNet.aspx
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 31, 2009 4:22 AM
  • User-1937266229 posted

     hey dude

    thanks for the links but there were not quite what i was looking for

     i have however managed to piece together some code that does the job perfect.

     

    <%@  Import Namespace="System.Drawing" %>
    <%@  Import Namespace="System.Drawing.Drawing2D" %>
    <%@  Import Namespace="System.Drawing.Imaging" %>
    <script language="vb" runat="server">
    Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs)

       Dim filepath As String = Server.MapPath(".") & "/Images/"
       Dim uploadedFiles As HttpFileCollection = Request.Files
       Dim i As Integer = 0

       Do Until i = uploadedFiles.Count
         Dim userPostedFile As HttpPostedFile = uploadedFiles(i)

         Try
            If (userPostedFile.ContentLength > 0 ) Then
               'random name
                   'Dim timestamp = year(now) & right("0" & month(now),2) & right("0" & day(now),2) & right("0" & hour(now),2) & right("0" & minute(now),2) & right("0" & second(now),2)
               
                Dim RandomString as String = System.Guid.NewGuid().ToString()


                       
                Dim filename As String = userPostedFile.FileName

                ' Create a bitmap of the content of the fileUpload control in memory
                Dim originalBMP As New Bitmap(userPostedFile.InputStream)
               
                ' Calculate the new image dimensions
                Dim origWidth As Integer = originalBMP.Width
                Dim origHeight As Integer = originalBMP.Height
                Dim sngRatio As Integer = origWidth / origHeight
                Dim newWidth As Integer = 300
                Dim newHeight As Integer = newWidth / sngRatio
               
                ' Create a new bitmap which will hold the previous resized bitmap
                Dim newBMP As New Bitmap(originalBMP, newWidth, newHeight)
               
                ' Create a graphic based on the new bitmap
                Dim oGraphics As Graphics = Graphics.FromImage(newBMP)
                ' Set the properties for the new graphic file
                oGraphics.SmoothingMode = SmoothingMode.AntiAlias
                oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic
               
                ' Draw the new graphic based on the resized bitmap
                oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight)
                ' Save the new graphic file to the server
                newBMP.Save((filepath & RandomString) + filename)
               
                ' Once finished with the bitmap objects, we deallocate them.
                originalBMP.Dispose()
                newBMP.Dispose()
                oGraphics.Dispose()   
               
                Image1.ImageUrl = "All images uploaded"      
                'Label1.Text += filename & "<br/>" & userPostedFile.ContentType
                'Image1.ImageUrl = "Images/" & RandomString & filename
                'Image1.Visible = True

            End If
           
         Catch ex As Exception
            Label1.Text += "Error:<br>" & ex.Message
           
         End Try
         i += 1
       Loop
      
          
          
    End Sub
    </script>
    <!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">
        <title>Upload and Resize</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="fileUpload" runat="server" /><br />
    <asp:FileUpload ID="fileUpload2" runat="server" /><br />
    <asp:FileUpload ID="fileUpload3" runat="server" /><br />
    <asp:FileUpload ID="fileUpload4" runat="server" /><br />
    <br /><br />
    <asp:Button ID="uploadButton" runat="server" Text="Upload!" OnClick="Button1_Click" />

    <br /><br />
    <asp:Label ID="label1" runat="server"></asp:Label> <br /><br />

    <!--<asp:Image ID="Image1" ImageUrl="" runat="server" Visible="false" /> -->

    </form>
    </body>
    </html>

     that will upload and resize multiple images and add a timestamp at the beginning.

    If anyone can improve this code in any way then please feel free too as i am still very new at asp.net.

    thanks again for the help.

    Andy

    Saturday, February 7, 2009 11:43 PM
  • User-1937266229 posted

     Hey Dudes

     I am using the above code which seems to work perfect in firefox but fails in IE

    I get this error when trying to upload an image

    Error:
    The given path's format is not supported.


    if anyone has any idea how to fix this then i would be most greatfull.

    here is my code

    <%@  Import Namespace="System.Drawing" %>
    <%@  Import Namespace="System.Drawing.Drawing2D" %>
    <%@  Import Namespace="System.Drawing.Imaging" %>
    <script language="vb" runat="server">
    Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs)

       Dim filepath As String = Server.MapPath(".") & "/Images/"
       Dim uploadedFiles As HttpFileCollection = Request.Files
       Dim i As Integer = 0
       Dim uploadedimgs=New ArrayList
      
       Do Until i = uploadedFiles.Count
         Dim userPostedFile As HttpPostedFile = uploadedFiles(i)

         Try
            If (userPostedFile.ContentLength > 0 ) Then
           
               'random name
                Dim RandomString as String = System.Guid.NewGuid().ToString()
                       
                Dim filename As String = userPostedFile.FileName

                ' Create a bitmap of the content of the fileUpload control in memory
                Dim originalBMP As New Bitmap(userPostedFile.InputStream)
               
                ' Calculate the new image dimensions
                Dim origWidth As Integer = originalBMP.Width
                Dim origHeight As Integer = originalBMP.Height
                Dim sngRatio As Integer = origWidth / origHeight
                Dim newWidth As Integer = 300
                Dim newHeight As Integer = newWidth / sngRatio
               
                ' Create a new bitmap which will hold the previous resized bitmap
                Dim newBMP As New Bitmap(originalBMP, newWidth, newHeight)
               
                ' Create a graphic based on the new bitmap
                Dim oGraphics As Graphics = Graphics.FromImage(newBMP)
                ' Set the properties for the new graphic file
                oGraphics.SmoothingMode = SmoothingMode.AntiAlias
                oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic
               
                ' Draw the new graphic based on the resized bitmap
                oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight)
                ' Save the new graphic file to the server
                newBMP.Save((filepath & RandomString) + filename)

                'add each image to arraylist
                uploadedimgs.Add(RandomString & filename)
                rb.DataSource=uploadedimgs
                rb.DataBind()
               
                ' Once finished with the bitmap objects, we deallocate them.
                originalBMP.Dispose()
                newBMP.Dispose()
                oGraphics.Dispose()   
               
                Label1.Text = "All images uploaded"

            End If
           
         Catch ex As Exception
            Label1.Text += "Error:<br>" & ex.Message
           
         End Try
         i += 1
       Loop
      
    End Sub
    </script>
    <!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">
        <title>Upload and Resize</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="fileUpload" runat="server" /><br />
    <asp:FileUpload ID="fileUpload2" runat="server" /><br />
    <asp:FileUpload ID="fileUpload3" runat="server" /><br />
    <asp:FileUpload ID="fileUpload4" runat="server" /><br />
    <br /><br />
    <asp:Button ID="uploadButton" runat="server" Text="Upload!" OnClick="Button1_Click" />

    <br /><br />
    <asp:Label ID="label1" runat="server"></asp:Label> <br /><br />

    <asp:DropDownList id="rb" runat="server" />

    </form>
    </body>
    </html>

    Cheers

    Andy

    Wednesday, February 11, 2009 9:43 AM
  • User-449803809 posted
    I am using this code for creating thumbnail (changing image size) Using C#

    ===============================
    public bool ThumbnailCallback()
    {
    return false;
    }

    public string resizeImage(string pathFrom, string pathTo, string path)
    {
    string functionReturnValue = null;

    try
    {
    //Create the delegate
    System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = default(System.Drawing.Image.GetThumbnailImageAbort);
    dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

    System.Drawing.Image fullSizeImg = default(System.Drawing.Image);
    fullSizeImg = System.Drawing.Image.FromFile(pathFrom);

    System.Drawing.Image thumbNailImg = default(System.Drawing.Image);
    thumbNailImg = fullSizeImg.GetThumbnailImage(100, 100, dummyCallBack, IntPtr.Zero);

    //check and create directories if necessary
    if (!Directory.Exists(path))
    {
    //create it if it doesn't
    Directory.CreateDirectory(path);
    }

    thumbNailImg.Save(pathTo);
    //GC.Collect()

    //Clean up / Dispose...
    thumbNailImg.Dispose();

    functionReturnValue = "0";
    }

    catch (Exception Err)
    {
    functionReturnValue = Err.Message;
    }
    return functionReturnValue;
    }

    ============================

    converted version to VB
    ============================
    Public Function ThumbnailCallback() As Boolean
    Return False
    End Function

    Public Function resizeImage(ByVal pathFrom As String, ByVal pathTo As String, ByVal path As String) As String

    Dim functionReturnValue As String = Nothing
    Try
    'Create the delegate
    Dim dummyCallBack As System.Drawing.Image.GetThumbnailImageAbort = Nothing
    dummyCallBack = New System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback)

    Dim fullSizeImg As System.Drawing.Image = Nothing
    fullSizeImg = System.Drawing.Image.FromFile(pathFrom)

    Dim thumbNailImg As System.Drawing.Image = Nothing
    thumbNailImg = fullSizeImg.GetThumbnailImage(100, 100, dummyCallBack, IntPtr.Zero)

    'check and create directories if necessary
    If Not Directory.Exists(path) Then
    'create it if it doesn't
    Directory.CreateDirectory(path)
    End If

    thumbNailImg.Save(pathTo)
    'GC.Collect()

    'Clean up / Dispose...
    thumbNailImg.Dispose()

    functionReturnValue = "0"

    Catch Err As Exception
    functionReturnValue = Err.Message
    End Try

    Return functionReturnValue
    End Function
    ============================

    and it's working perfectly with me, you can check www.myphotoup.com , gallery page
    Wednesday, February 18, 2009 3:44 AM