Search code examples
vb.netimagealgorithmresizeaspect-ratio

Resize image and keep aspect ratio


I'm trying to make zoom in/out buttons, but for whatever reason I just can't figure out how to maintain the aspect ratio and resize the image by - say 90% or 110%

The issue is that I'm trying to make it so that when you click the zoom out button 4 times, then click the zoom in button 4 times, the image would be its original size. There's no defined width since I'm trying to make the new width be 90%/110% of the existing width, but obviously multiplying by 0.9 and 1.1 doesn't do that correctly.

I currently have the following code..

    Dim source As New Bitmap(PictureBox1.Image)
    Dim NewWidth As Integer = source.Width * 0.9
    Dim NewHeight As Integer = NewWidth * (source.Height / source.Width)

Any help is appreciated. I'm sure I'm just over-thinking it again, but some guidance would be appreciated :)


Solution

  • The best approach is to begin each resize operation with a copy of the original image. Have your buttons represent the total zoom factor (so say add 0.1 zoom for the + and subtract 0.1 zoom for the -).

    You want to start with the original image each time because otherwise successive operations will quickly distort the image due to the interpolation inherent in zooming in and out.