I am new to vb.NET and I have decided to make an image viewer, and what I want to do is resize the image it loads to fit the picture box, how do I do this? My image is a System.Drawing.Image object.

Recommended Answers

All 2 Replies

try this:

Public Sub ResizeImage(ByVal pathToImg As String, ByVal pictureCtrl As PictureBox, Optional ByVal SizeMode As PictureBoxSizeMode = PictureBoxSizeMode.CenterImage)
        Try
            pictureCtrl.Image = Nothing
            pictureCtrl.SizeMode = SizeMode
            If System.IO.File.Exists(pathToImg) Then
                Dim imgOrg, imgShow As Bitmap
                Dim g As Graphics
                Dim divideBy, divideByH, divideByW As Double
                imgOrg = DirectCast(Bitmap.FromFile(pathToImg), Bitmap)

                divideByW = imgOrg.Width / pictureCtrl.Width
                divideByH = imgOrg.Height / pictureCtrl.Height
                If divideByW > 1 Or divideByH > 1 Then
                    divideBy = CDbl(IIf(divideByW > divideByH, divideByW, divideByH))

                    imgShow = New Bitmap(CInt(CDbl(imgOrg.Width) / divideBy), CInt(CDbl(imgOrg.Height) / divideBy))
                    imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution)
                    g = Graphics.FromImage(imgShow)
                    g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                    g.DrawImage(imgOrg, New Rectangle(0, 0, CInt(CDbl(imgOrg.Width) / divideBy), CInt(CDbl(imgOrg.Height) / divideBy)), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel)
                Else
                    imgShow = New Bitmap(imgOrg.Width, imgOrg.Height)
                    imgShow.SetResolution(imgOrg.HorizontalResolution, imgOrg.VerticalResolution)
                    g = Graphics.FromImage(imgShow)
                    g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                    g.DrawImage(imgOrg, New Rectangle(0, 0, imgOrg.Width, imgOrg.Height), 0, 0, imgOrg.Width, imgOrg.Height, GraphicsUnit.Pixel)
                End If
                g.Dispose()
                imgOrg.Dispose()
                pictureCtrl.Image = imgShow
            Else
                pictureCtrl.Image = Nothing
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

Hey thanks, that worked, but when I load some images, the bottom of the image gets cut off, about 50 pixels are cut off. Is there any way to fix this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.