Monday, June 29, 2009

Resize an image's dimensions and Save it as a file in different extension

The following VB.NET code is used to resize the dimensions of an image file dynamically and save it as a file in different extension.

For example, we may want to resize the dimensions of a set of image files(1024 x 1024 jpg images) from a folder into 600 x 600 and save it as a bmp files.

We need to resize the image without affecting the quality of the image.


Code to resize an image and save it as a file in different extension:

[CODE]
Private Sub btnResize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResize.Click

'Original Image
Dim img As New Bitmap("C:\Users\Raj\Desktop\Niagara_Pictures\DSC06721.JPG")

OrigPictureBox.Image = img

Dim resizedImg As Image = Nothing

'Resize the Image to 300 x 300 dimension
resizedImg = ResizeImage(img, 300, 300)


If Not resizedImg Is Nothing Then


ResizedPictureBox.Image = resizedImg

'Save the Image file in different extension (.bmp)
'You can use OpenFileDialog to get the File Name


resizedImg.Save("E:\Test.bmp", Imaging.ImageFormat.Bmp)

End If


End Sub

//Function to return the resized image
Private Function ResizeImage(ByVal img As Image, ByVal NewWidth As Integer, ByVal NewHeight As Integer) As Image

Dim resizedImg As Image = Nothing
Try
Dim bmp As Bitmap = New Bitmap(NewWidth, NewHeight)
Dim gr As Graphics = Graphics.FromImage(bmp)
//Resize the image without affecting the quality
gr.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
gr.DrawImage(img, 0, 0, Width, Height)

resizedImg = bmp

Catch ex As Exception
resizedImg = Nothing
End Try

Return resizedImg

End Function
[/CODE]


The final image will be with the new dimensoins but with high quality.

No comments:

Post a Comment