65.9K
CodeProject is changing. Read more.
Home

Resizing images while uploading in ASP.NET

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (3 votes)

Jul 15, 2011

CPOL
viewsIcon

38472

A method for resizing images automatically when they are being uploaded.

Tired of big sized images uploaded on your website? Well, this is a way to resize images automatically in the code when they are being uploaded, to make their size smaller.

Imports System.Drawing
Imports System.Drawing.Drawing2D

Dim gu As New Guid
gu = Guid.NewGuid
Dim ext As String = Path.GetExtension(FileUpload1.FileName)
ImageName = gu.ToString & ext
FileUpload1.SaveAs(Server.MapPath("~/DynamicImages/News/" & ImageName))
Using fl = File.OpenRead(Server.MapPath("~/DynamicImages/News/" & ImageName))
    Using thumbFile = File.Create(Server.MapPath("~/DynamicImages/News/thumbnails/" & ImageName))
        ResizeImage(0.1, fl, thumbFile)
    End Using
End Using

Private Sub ResizeImage(ByVal scaleFactor As Double, ByVal fromStream As Stream, ByVal toStream As Stream)
    Using image__1 = Image.FromStream(fromStream)
        'Dim newWidth = CInt(image__1.Width * scaleFactor)
        ' Dim newHeight = CInt(image__1.Height * scaleFactor)
        Dim newWidth = 150
        Dim newHeight = 150

        Using thumbnailBitmap = New Bitmap(newWidth, newHeight)
            Using thumbnailGraph = Graphics.FromImage(thumbnailBitmap)
                thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality
                thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality
                thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic

                Dim imageRectangle = New Rectangle(0, 0, newWidth, newHeight)
                thumbnailGraph.DrawImage(image__1, imageRectangle)

                thumbnailBitmap.Save(toStream, image__1.RawFormat)
            End Using
        End Using
    End Using
End Sub

The thing here is in the resize image function, which makes the size of your images smaller. Note that I am storing the small images in a folder named ~/DynamicImages/News/thumbnails/, and I am adding to the images a unique ID using the GUID.