devxlogo

ResizeImage – Resize an image, and optionally keep the original ratio automatically

ResizeImage – Resize an image, and optionally keep the original ratio automatically

' Resize the specified image file - The new dimensions are expressed in ' percentage of the original size.' The resized image overwrites the original file.' Note: requires the GetImageFormat function'' Example:'    ResizeImage("D:sample.gif", 50.0, 50.0) ' make the image half the ' original size'    ResizeImage("D:sample.gif", 200.0, 300.0) ' double the width and triple ' the heightSub ResizeImage(ByVal imgPath As String, ByVal widthPerc As Double, _    ByVal heightPerc As Double)    ' throw an exception if not both arguments are positive values    If widthPerc ' get the image's current width/height    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(imgPath)    currWidth = img.Width    currHeight = img.Height    img.Dispose()    ' calculate the new size in pixel    newWidth = currWidth * widthPerc / 100    newHeight = currHeight * heightPerc / 100    ' call the overloaded method that takes explicit width/height in pixels    ResizeImage(imgPath, newWidth, newHeight)End Sub' This overloaded version takes the new width/height in pixel,'  instead of the percentage of the original size.' Either the width/height (but not both) can be 0,'  and the size will be calculate to maintain the ratio of the original image' Example:'    ResizeImage("D:sample.gif", 100, 50) ' resize to 100x50'    ResizeImage("D:sample.gif", 100, 0)  ' the height will be calculated ' according to the new widthSub ResizeImage(ByVal imgPath As String, ByVal width As Integer, _    ByVal height As Integer)    ' throw an exception if both arguments are not positive integers    If width ' select the format of the image to write according to the current extension    Dim imgFormat As System.Drawing.imaging.ImageFormat = GetImageFormat _        (imgPath)    ' open the image file    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(imgPath)    ' if either the specified height or width are 0, calculate it to maintain     ' the same ratio of the original image    If width ' create a new empty bitmpat with the specified size    Dim bmp As New System.Drawing.Bitmap(width, height)    ' retrieve a canvas object that allows to draw on the empty bitmap    Dim g As System.Drawing.Graphics = System.Drawing.Graphics.FromImage( _        DirectCast(bmp, System.Drawing.Image))    ' copy the original image on the canvas, and thus on the new bitmap,    '  with the new size    g.DrawImage(img, 0, 0, width, height)    ' close the original image    img.Dispose()    ' save the new image with the proper format    bmp.Save(imgPath, imgFormat)    bmp.Dispose()End Sub

devx-admin

Share the Post: