s1ckOh
Well-known member
Sorry if this thread is in the wrong section.
Over the last few days I have combed thread after thread looking for a way to resize my images to fit inside a div container only 240px by 240px but still keep the aspect ratio of the original picture. No one thread had an easy way but I was able to put together this bit of code to make my dreams come true. I would give credit where it's due but I don't remember where it all came from.
A bit of code to create a thumbnail of a large image keeping the aspect ratio:
If there is an easier way to do this, which I'm sure there is, please share.
Over the last few days I have combed thread after thread looking for a way to resize my images to fit inside a div container only 240px by 240px but still keep the aspect ratio of the original picture. No one thread had an easy way but I was able to put together this bit of code to make my dreams come true. I would give credit where it's due but I don't remember where it all came from.
A bit of code to create a thumbnail of a large image keeping the aspect ratio:
VB.NET:
Public Sub ResizeImage()
Dim iPath As String = Path.Combine(Server.MapPath("../images"), "[File Name]")
Dim NewPath As String = Path.Combine(Server.MapPath("../thumbs"), "[File Name]")
Using img As Image = New Bitmap(iPath)
Dim OriginalSize As Size = img.Size
Dim NewSize As Size
NewSize.Height = 240 'Maximum desired height
NewSize.Width = 240 'Maximum desired width
Dim FinalSize As Size = ProportionalSize(OriginalSize, NewSize)
Using img2 As Image = img.GetThumbnailImage(FinalSize.Width, FinalSize.Height, New Image.GetThumbnailImageAbort(AddressOf Abort), IntPtr.Zero)
img2.Save(NewPath)
End Using
End Using
Image1.ImageUrl = "../thumbs/[File Name]"
End Sub
Private Function Abort() As Boolean
Return False
End Function
Function ProportionalSize(ByVal imageSize As Size, ByVal MaxW_MaxH As Size) As Size
Dim multBy As Double = 1.01
Dim w As Double = imageSize.Width
Dim h As Double = imageSize.Height
While w < MaxW_MaxH.Width AndAlso h < MaxW_MaxH.Height
w = imageSize.Width * multBy
h = imageSize.Height * multBy
multBy = multBy + 0.001
End While
While w > MaxW_MaxH.Width OrElse h > MaxW_MaxH.Height
multBy = multBy - 0.001
w = imageSize.Width * multBy
h = imageSize.Height * multBy
End While
If imageSize.Width < 1 Then
imageSize = New Size(imageSize.Width + -imageSize.Width + 1, imageSize.Height - imageSize.Width - 1)
End If
If imageSize.Height < 1 Then
imageSize = New Size(imageSize.Width - imageSize.Height - 1, imageSize.Height + -imageSize.Height + 1)
End If
imageSize = New Size(Convert.ToInt32(w), Convert.ToInt32(h))
Return imageSize
End Function
If there is an easier way to do this, which I'm sure there is, please share.