vb.net

How Can I re-size an image in VB.Net


I need it so that in my code if something evaluates to true it changes the image location and size.

This is my code so far:

With picValueTwentySix
   .Location = New Point(302, 134)
   .Size = New System.Drawing.Size(169, 40)
   .SizeMode = PictureBoxSizeMode.Zoom
End With

Anybody know why it isn't re-sizing?

Thanks!


Solution

  • As everyone has already mentioned, you need to work the the image. Here is a function I made up for ease of use.

    Public Function ResizeImage(ByVal image As Image, ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image
        Try
            Dim newWidth As Integer
            Dim newHeight As Integer
            If preserveAspectRatio Then
                Dim originalWidth As Integer = image.Width
                Dim originalHeight As Integer = image.Height
                Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
                Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)
                Dim percent As Single = IIf(percentHeight < percentWidth, percentHeight, percentWidth)
                newWidth = CInt(originalWidth * percent)
                newHeight = CInt(originalHeight * percent)
            Else
                newWidth = size.Width
                newHeight = size.Height
            End If
    
            Dim newImage As Image = New Bitmap(newWidth, newHeight)
            Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
                graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
            End Using
    
            Return newImage
    
        Catch ex As Exception
            Return image
        End Try
    End Function
    

    Basically it creates a new blank graphic to the dimensions you request, then copies the original image to it while scaling it to fit. I think if you step throw it a line at a time you should be pretty self explanatory, but ask if you have questions...