Resize an uploaded image

I'm using this code (VB) to upload an image to an upload folder on my site:

 Sub UploadImage()
        If Not (FileUpload1.PostedFile Is Nothing) Then 'Check to make sure we actually have a file to upload
            labelStatus.Text = ""
            Dim strLongFilePath As String = FileUpload1.PostedFile.FileName
            Dim intFileNameLength As Integer = InStr(1, StrReverse(strLongFilePath), "\")
            Dim strFileName As String = Mid(strLongFilePath, (Len(strLongFilePath) - intFileNameLength) + 2)
            Dim a As String = Server.MapPath("")
            a = Strings.Replace(a, "workshops", "")
            Select Case FileUpload1.PostedFile.ContentType
                Case "image/pjpeg", "image/jpeg" 'Make sure we are getting a valid JPG image
                    FileUpload1.PostedFile.SaveAs(a & "\uploads\images\" & UserID & "_" & strFileName)
                    labelStatus.Text = strFileName & " was uploaded successfully"
                       Case Else
                    'Not a valid jpeg image
                    labelStatus.Text = "Not a valid jpg/jpeg image"
            End Select
        End If
    End Sub

This code works great...what I need is how do I integrate a function to resize the image to 200x200 before it is saved?  (or save it, then resize it, then resave it- whatever is easier)
Specifically, I need to know how to do the resize while using the code above.  I've found various chunks of code about resizing an image (ie. "true image resizing" article from 4 guys rozilla), but have no idea how to integrate such code with the code I have above.  I need a solution that can integrate with the code I already have.

Thanks!
arthurh88Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CutSackCommented:
Hi,

I do this in one of my applications, by first loading the image into a Memory Stream, then resizing in memory.

My sample code resizes the image to a maximum width/height but keeps the ratio of the original.

I've modified your code and included a function that I use to do the resize.
 Sub UploadImage()
        If Not (FileUpload1.PostedFile Is Nothing) Then 'Check to make sure we actually have a file to upload
            labelStatus.Text = ""
            Dim strLongFilePath As String = FileUpload1.PostedFile.FileName
            Dim intFileNameLength As Integer = InStr(1, StrReverse(strLongFilePath), "\")
            Dim strFileName As String = Mid(strLongFilePath, (Len(strLongFilePath) - intFileNameLength) + 2)
            Dim a As String = Server.MapPath("")
            a = Strings.Replace(a, "workshops", "")
            Select Case FileUpload1.PostedFile.ContentType
                Case "image/pjpeg", "image/jpeg" 'Make sure we are getting a valid JPG image
 
' Get the image into a Memory Stream
        Dim ImageStream As Stream
        Dim ResizedStream As MemoryStream
        ImageStream = FileUpload1.PostedFile.InputStream
 
        ResizedStream = ResizeImage(ImageStream)
        ResizedStream.Seek(0, SeekOrigin.Begin)
 
        Dim FS as FileStream = File.Open(a & "\uploads\images\" & UserID & "_" & strFileName
 
            FS.Write(ResizedStream.ToArray(), 0, CInt(ResizedStream.Length - 1))
        FS.close()
 
                    labelStatus.Text = strFileName & " was uploaded successfully"
                       Case Else
                    'Not a valid jpeg image
                    labelStatus.Text = "Not a valid jpg/jpeg image"
            End Select
        End If
    End Sub
 
 
 
Private Function ResizeImage(ByRef InputStream As Stream, MaxPhotoWidth as Integer, MaxPhotoHeight as Integer) As MemoryStream
 
        ' Takes a File Stream reference object and converts it to the appropriately sized byte stream
        Dim OldImage As System.Drawing.Image
        Dim NewHeight As Integer
        Dim NewWidth As Integer
        Dim ic As New ImageConverter
        Dim OutputStream As New MemoryStream
 
        MaxPhotoHeight = APP_CONFIG.MaxPhotoHeight
        MaxPhotoWidth = APP_CONFIG.MaxPhotoWidth
 
        ' Create the new image from the Original
        OldImage = System.Drawing.Image.FromStream(InputStream)
        'Determine what dimension is off by more 
        Dim deltaWidth As Integer = OldImage.Width - MaxPhotoWidth
        Dim deltaHeight As Integer = OldImage.Height - MaxPhotoHeight
        Dim scaleFactor As Double
 
        If (OldImage.Height <= MaxPhotoHeight And OldImage.Width <= MaxPhotoWidth) Then
            ' Dont stretch a smaller original
            NewHeight = OldImage.Height
            NewWidth = OldImage.Width
        Else
            ' Resize the image maintaining the original image aspect ratio.
            If deltaHeight > deltaWidth Then
                'Scale by the height 
                scaleFactor = MaxPhotoHeight / OldImage.Height
            Else
                'Scale by the Width 
                scaleFactor = MaxPhotoWidth / OldImage.Width
            End If
 
            NewHeight = CInt(OldImage.Height * scaleFactor)
            NewWidth = CInt(OldImage.Width * scaleFactor)
 
        End If
 
        'Create the new image
        Dim NewImage As New System.Drawing.Bitmap(OldImage, NewWidth, NewHeight)
 
        ' Convert the image to a stream ready to save
        OldImage.Dispose()
 
        NewImage.Save(OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
 
        Return OutputStream
 
 
    End Function

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CutSackCommented:
Sorry, line 17 should be something like:

        ResizedStream = ResizeImage(ImageStream, <your max width value>, <your max height value>)
0
arthurh88Author Commented:
hi Cutsack, the code works great...I was able to get it to work, and I am prepared to give you points, but is there any way to have the file properly shrink upon resaving?

I uploaded a 100KB photo that was 500x500, resized it to 100x100 and it saved as 100KB...even though it is only 1/5th the size.   why is the filesize the same and is there anyway that the filesize can properly shrink?

0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

CutSackCommented:
Hi arthurh88,

I ran the code myself and resized a 1024x800 image to 80x80 and the size changed from 289Kb to 2.8Kb.

Can you post your final code and I will try it out here and see what happens.
0
arthurh88Author Commented:
Here is the full code, and a test page that you can use:
www.theravive.com/workshops/test.aspx



Imports System.Drawing
Imports System.io
Partial Class test
    Inherits System.Web.UI.Page
 
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        UploadImage()
    End Sub
    Sub UploadImage()
        Dim UserID As String = ""
        If Not (FileUpload1.PostedFile Is Nothing) Then 'Check to make sure we actually have a file to upload
            labelStatus.Text = ""
            Dim strLongFilePath As String = FileUpload1.PostedFile.FileName
            Dim intFileNameLength As Integer = InStr(1, StrReverse(strLongFilePath), "\")
            Dim strFileName As String = Mid(strLongFilePath, (Len(strLongFilePath) - intFileNameLength) + 2)
 
            Dim a As String = Server.MapPath("")
            a = Strings.Replace(a, "workshops", "")
 
            Select Case FileUpload1.PostedFile.ContentType
                Case "image/pjpeg", "image/jpeg" 'Make sure we are getting a valid JPG image
 
 
                    Dim filesize As String = Convert.ToInt32(FileUpload1.PostedFile.ContentLength / 1000)
                    If Val(filesize) > 200 Then
                        labelStatus.Text = "Cannot upload, the file is too large.  Maximum size = 200KB"
                        Exit Sub
                    End If
 
 
                    ' Get the image into a Memory Stream
                    Dim ImageStream As Stream
                    Dim ResizedStream As MemoryStream
                    ImageStream = FileUpload1.PostedFile.InputStream
 
                    ResizedStream = ResizeImage(ImageStream, 200, 200)
                    ResizedStream.Seek(0, SeekOrigin.Begin)
                    FileUpload1.PostedFile.SaveAs(a & "\uploads\images\" & strFileName)
                    Dim FS As FileStream = File.Open(a & "\uploads\images\" & strFileName, FileMode.Open)
 
                    FS.Write(ResizedStream.ToArray(), 0, CInt(ResizedStream.Length - 1))
                    FS.Close()
 
 
 
                    labelStatus.Text = strFileName & " was uploaded successfully to: www.theravive.com/uploads/images/" & strFileName
 
                Case Else
                    'Not a valid jpeg image
                    labelStatus.Text = "Not a valid jpg/jpeg image"
            End Select
        End If
 
 
 
 
    End Sub
 
    Private Function ResizeImage(ByRef InputStream As Stream, ByVal MaxPhotoWidth As Integer, ByVal MaxPhotoHeight As Integer) As MemoryStream
 
        ' Takes a File Stream reference object and converts it to the appropriately sized byte stream
        Dim OldImage As System.Drawing.Image
        Dim NewHeight As Integer
        Dim NewWidth As Integer
        Dim ic As New ImageConverter
        Dim OutputStream As New MemoryStream
 
        'MaxPhotoHeight = APP_CONFIG.MaxPhotoHeight
        ' MaxPhotoWidth = APP_CONFIG.MaxPhotoWidth
 
        ' Create the new image from the Original
        OldImage = System.Drawing.Image.FromStream(InputStream)
        'Determine what dimension is off by more 
        Dim deltaWidth As Integer = OldImage.Width - MaxPhotoWidth
        Dim deltaHeight As Integer = OldImage.Height - MaxPhotoHeight
        Dim scaleFactor As Double
 
        If (OldImage.Height <= MaxPhotoHeight And OldImage.Width <= MaxPhotoWidth) Then
            ' Dont stretch a smaller original
            NewHeight = OldImage.Height
            NewWidth = OldImage.Width
        Else
            ' Resize the image maintaining the original image aspect ratio.
            If deltaHeight > deltaWidth Then
                'Scale by the height 
                scaleFactor = MaxPhotoHeight / OldImage.Height
            Else
                'Scale by the Width 
                scaleFactor = MaxPhotoWidth / OldImage.Width
            End If
 
            NewHeight = CInt(OldImage.Height * scaleFactor)
            NewWidth = CInt(OldImage.Width * scaleFactor)
 
        End If
 
        'Create the new image
        Dim NewImage As New System.Drawing.Bitmap(OldImage, NewWidth, NewHeight)
 
        ' Convert the image to a stream ready to save
        OldImage.Dispose()
 
        NewImage.Save(OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
 
        Return OutputStream
 
 
    End Function
 
End Class

Open in new window

0
arthurh88Author Commented:
Hey, nm i think i figured it out.  I  changed the file.open to file.create and that woked.

thanks a lot!!
0
arthurh88Author Commented:
thank you, great code!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.