Resize memory stream image

Experts, I am using the code below to allow the user to insert an image into a datatable. The datagridview displays part numbers, pricing and description. I want the user to be able to add an image for that item. I want to resize the image that the user selects with a savefiledialog. I need to have a fixed height and resize the width proportionally.

Can you please help me with this.
        Dim sd As New SaveFileDialog()

        sd.Title = "Select product image"
        sd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        sd.Filter = "Bitmap|*.bmp|JPEG|*.jpg|Gif|*.gif|PNG|*.png"
        sd.FilterIndex = 2
        sd.RestoreDirectory = True

        If sd.ShowDialog() = DialogResult.OK Then
            If DataGridView1.SelectedRows.Count > 0 Then
                Dim intID As Integer = CInt(DataGridView1.SelectedRows(0).Cells("ID").Value)
                Dim row As DataRow = ds.Tables("dtTTOMaster").Rows.Find(intID)
                Using ms As New MemoryStream
                    Using fs As FileStream = File.OpenRead(sd.FileName)
                        ms.SetLength(fs.Length)
                        fs.Read(ms.GetBuffer(), 0, CInt(Fix(fs.Length)))
                    End Using
                    row("PartImage") = ms.ToArray
                End Using
            End If
        End If

Open in new window

BasicfarmerAsked:
Who is Participating?
 
CodeCruiserCommented:
Here is a function you can use


Public Shared Function ScaleImage(image As Image, maxWidth As Integer, maxHeight As Integer) As Bitmap
	Dim ratioX = CDbl(maxWidth) / image.Width
	Dim ratioY = CDbl(maxHeight) / image.Height
	Dim ratio = Math.Min(ratioX, ratioY)

	Dim newWidth = CInt(image.Width * ratio)
	Dim newHeight = CInt(image.Height * ratio)

	Dim newImage = New Bitmap(newWidth, newHeight)
	Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight)
	Dim bmp As New Bitmap(newImage)

	Return bmp
End Function

Open in new window

0
 
BasicfarmerAuthor Commented:
Thanks for the quick response....
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.