Link to home
Start Free TrialLog in
Avatar of arthurh88
arthurh88

asked on

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!
ASKER CERTIFIED SOLUTION
Avatar of CutSack
CutSack

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CutSack
CutSack

Sorry, line 17 should be something like:

        ResizedStream = ResizeImage(ImageStream, <your max width value>, <your max height value>)
Avatar of arthurh88

ASKER

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?

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.
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

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

thanks a lot!!
thank you, great code!