TechTutorials - Free Computer Tutorials  

Resize Images in ASP.NET 

Added: 11/21/2008, Hits: 4,519, Rating: 0, Comments: 0, Votes: 0
Add To Favorites | Comment on this article
Sometimes the quality of images should not be scratched if you resize as you want. This will help you resize the image before uploading. Hope this will helpful for all.

Call the function like this :ResizeImageProportionally(YourFileUploader.PostedFile.InputStream, FileName, Width, Height)

Following is the function definition.

Code :

Private Function ResizeImageProportionally(ByVal Stream As System.IO.Stream, ByVal strDestinationFileName As String, ByVal newWidth As Int32, ByVal newHeight As Int32) As Boolean
'String newFileName = String.Empty;

If Not Stream Is Nothing AndAlso newHeight > 0 AndAlso newWidth > 0 Then
' Create new stream.
' Dim stream As New FileStream(fileName, FileMode.Open, FileAccess.Read)

' Create new image.
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(Stream)

' Calculate proportional max width and height.
Dim oldWidth As Integer = image.Width
Dim oldHeight As Integer = image.Height
If (CDec(oldWidth) / CDec(oldHeight)) > (CDec(newWidth) / CDec(newHeight)) Then
Dim ratio As Decimal = CDec(newWidth) / oldWidth
newHeight = CInt((oldHeight * ratio))
Dim ratio As Decimal = CDec(newHeight) / oldHeight
newWidth = CInt((oldWidth * ratio))
End If

' Create a new bitmap with the same resolution as the original image.
Dim bitmap As New Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb)
bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution)

' Create a new graphic.
Dim graphics__1 As Graphics = Graphics.FromImage(bitmap)
graphics__1.InterpolationMode = InterpolationMode.HighQualityBicubic

' Create a scaled image based on the original.
graphics__1.DrawImage(image, New Rectangle(0, 0, newWidth, newHeight), New Rectangle(0, 0, oldWidth, oldHeight), GraphicsUnit.Pixel)

' Save the scaled image.
bitmap.Save(Server.MapPath("Images/") & strDestinationFileName, image.RawFormat)
End If
Return True
Catch ex As Exception
Throw ex
End Try
Return False
End Function

About the author:
This article was written by hareshmca

Comments (0)

Be the first to comment on this article

Related Items

7 Seconds Resources, Inc.

IT Showcase