Link to home
Start Free TrialLog in
Avatar of jtmerch
jtmerch

asked on

Asp.net Image Upload resizing.

Hell, I'm using ASP.net/VB.net to upload an image using "System.Web.UI.HtmlControls.HtmlInputFile".  I'm able to upload successfully ensuring that all images are jpeg but I'm looking for a way to determine the size of the image and compressing/resizing the image so I don't allow images that are over 1 meg in size, but I'll also resize it for them using an automated script.  Is this possible and does anyone have any tips/samples that could help me get there.

Any help is greatly appreciated.
Avatar of toddhd
toddhd

There is some at the bottom of this page (in C#) that addresses this issue:
http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=16935

Avatar of jtmerch

ASKER

Thanks this is helpful, any already done in VB.net that you know of?
In .NET, the default file upload max size is 4Mb. Most of the time, the problem is allowing LARGER files to upload.

You basically have two options:

1) Upload the file normally, then inspect its file size on the server side, using the standard FileInfo properties. If it is too large, either resize it, or delete it, and notify the end user of the problem. This is the method I'd reccomend.

2) Change the max file size. If you examine the machine.config file, you'll see a passage like this:
<httpRuntime
 executionTimeout="90"
 maxRequestLength="4096"
 useFullyQualifiedRedirectUrl="false"
 minFreeThreads="8"
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="100"
/>

The MaxRequestLength is the parameter that controls the max file size. Make this the size of the maximum file size, and you are good to go. The downside? This is global. If you want small image files, but to allow large zip files, you can't. All uploads are restricted.
Imports System.Drawing
Imports System.Drawing.Imaging

Public Class ResizeImage

    Private _CreateThumbnail As Boolean
    Private _ThumbX, _ThumbY, _FullSizeX, _FullSizeY As Integer
    Private UnacceptableImageFormats As ArrayList

    Public Property CreateThumbnail() As Boolean
        Get
            Return _CreateThumbnail
        End Get
        Set(ByVal Value As Boolean)
            _CreateThumbnail = Value
        End Set
    End Property
    Public Property FullSizeX() As Integer
        Get
            Return _FullSizeX
        End Get
        Set(ByVal Value As Integer)
            _FullSizeX = Value
        End Set
    End Property
    Public Property FullSizeY() As Integer
        Get
            Return _FullSizeY
        End Get
        Set(ByVal Value As Integer)
            _FullSizeY = Value
        End Set
    End Property
    Public Property ThumbX() As Integer
        Get
            Return _ThumbX
        End Get
        Set(ByVal Value As Integer)
            _ThumbX = Value
        End Set
    End Property
    Public Property ThumbY() As Integer
        Get
            Return _ThumbY
        End Get
        Set(ByVal Value As Integer)
            _ThumbY = Value
        End Set
    End Property

    Public Sub New(ByVal CreateThumbnail As Boolean, ByVal FullSizeX As Integer, ByVal FullSizeY As Integer)
        _CreateThumbnail = CreateThumbnail
        _FullSizeX = FullSizeX
        _FullSizeY = FullSizeY

        UnacceptableImageFormats = New ArrayList(10)
        With UnacceptableImageFormats
            .Add(Imaging.PixelFormat.Format1bppIndexed)
            .Add(Imaging.PixelFormat.Format4bppIndexed)
            .Add(Imaging.PixelFormat.Format8bppIndexed)
            .Add(Imaging.PixelFormat.Undefined)
            .Add(Imaging.PixelFormat.DontCare)
            .Add(Imaging.PixelFormat.Format16bppArgb1555)
            .Add(Imaging.PixelFormat.Format16bppGrayScale)
        End With
    End Sub
    Public Function ResizeImage(ByVal ImageSource As String) As String
        Dim IncomingImage As System.Drawing.Image
        Dim OutputBitmap As Bitmap
        Dim JpegCodec As ImageCodecInfo
        Dim JpegEncodeParams As EncoderParameters
        Dim NewSize As Size
        Dim fiSource As New IO.FileInfo(ImageSource)
        Dim fsSource As IO.FileStream
        Dim fiDestination As New IO.FileInfo(ImageSource)
        Dim NewFilename As String

        fiSource.MoveTo(fiSource.DirectoryName & "\TEMP_" & fiSource.Name)
        fsSource = fiSource.OpenRead()
        IncomingImage = IncomingImage.FromStream(fsSource)

        OutputBitmap = RedrawImage(IncomingImage, FullSizeX, FullSizeY)
        If fiSource.Extension = ".gif" Then
            NewFilename = fiDestination.Name
            OutputBitmap.Save(fiDestination.FullName)
        Else
            JpegCodec = ReturnJpegCodec()
            JpegEncodeParams = ReturnEncoderParams()
            NewFilename = fiDestination.Name.Replace(fiDestination.Extension, ".jpg")
            OutputBitmap.Save(fiDestination.FullName.Replace(fiDestination.Extension, ".jpg"), _
                JpegCodec, JpegEncodeParams)
        End If

        If CreateThumbnail Then
            OutputBitmap = RedrawImage(IncomingImage, ThumbX, ThumbY)
            If fiSource.Extension = ".gif" Then
                OutputBitmap.Save(fiDestination.DirectoryName & "/Thumbnails/" & fiDestination.Name)
            Else
                JpegCodec = ReturnJpegCodec()
                JpegEncodeParams = ReturnEncoderParams()
                OutputBitmap.Save(fiDestination.DirectoryName & "/Thumbnails/" & _
                    fiDestination.Name.Replace(fiDestination.Extension, ".jpg"), JpegCodec, JpegEncodeParams)
            End If
        End If

        fsSource.Close()
        OutputBitmap.Dispose()
        IncomingImage.Dispose()
        fiSource.Delete()

        Return NewFilename
    End Function

    Private Function RedrawImage(ByVal IncomingImage As Image, ByVal MaximumX As Integer, _
        ByVal MaximumY As Integer) As Bitmap
        Dim ResizedX, ResizedY As Integer
        Dim Bitmap As Bitmap
        Dim Graphic As Graphics
        Dim NewSize As Size

        ResizedY = CInt((IncomingImage.Height * MaximumX) / IncomingImage.Width)
        ResizedX = CInt((IncomingImage.Width * MaximumY) / IncomingImage.Height)

        If ResizedY >= MaximumY Then
            NewSize = New Size(ResizedX, MaximumY)
        Else
            NewSize = New Size(MaximumX, ResizedY)
        End If

        Bitmap = New Bitmap(IncomingImage, NewSize)
        Bitmap.SetResolution(72, 72)

        'Some graphic pixel formats prevent the image from being converted into an instance of Graphics.
        '   If this is the case, return just the resized bitmap without processing.
        If UnacceptableImageFormats.Contains(Bitmap.PixelFormat) Then Return Bitmap

        'All pixel formats that Microsoft says will generate exceptions have been loaded into the array
        '   above, yet some pixel formats are still throwing exceptions. Resorted to a Try / Catch block - AM
        Try
            Graphic = Graphics.FromImage(Bitmap)
        Catch
            Return Bitmap
        End Try

        Graphic.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
        Graphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        Graphic.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality

        Graphic.DrawImage(Bitmap, 0, 0)
        Graphic.Dispose()

        Return Bitmap
    End Function

    Private Function ReturnJpegCodec() As ImageCodecInfo
        Dim codecs As Imaging.ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()

        For Each codec As ImageCodecInfo In codecs
            If codec.MimeType.Equals("image/jpeg") Then Return codec
        Next
    End Function
    Private Function ReturnEncoderParams() As EncoderParameters
        Dim EncoderInstance As Encoder
        Dim EncoderParametersInstance As New EncoderParameters(2)
        Dim QualityParameter As EncoderParameter
        Dim ColorParameter As EncoderParameter

        EncoderInstance = Encoder.Quality
        QualityParameter = New EncoderParameter(EncoderInstance, 80L)
        EncoderParametersInstance.Param(0) = QualityParameter

        EncoderInstance = Encoder.ColorDepth
        ColorParameter = New EncoderParameter(EncoderInstance, 24L)
        EncoderParametersInstance.Param(1) = ColorParameter

        Return EncoderParametersInstance
    End Function

End Class
Avatar of jtmerch

ASKER

Hello, actually I'm wondering about automating hte resize of the image.  So I'll resize it for them if the file is too large.  Would you recommend this?  Is it just too much work and should I just tell them to go resize the image themselves if it's too large?

Thanks, for any help.
Imports System.Drawing.Image
Imports System.Drawing
Imports System.IO
Imports System.Text

Public Structure CropType
    Public Height As String
    Public Width As String
End Structure

Public Structure ResizeType
    Public Height As String
    Public Width As String
End Structure

Public Structure RotateType
    Public Degrees As String
End Structure

Public Class ImageTransform
    Public Crop As CropType
    Public Resize As ResizeType
    Public Rotate As RotateType
End Class


Public Class MyImage
    Public _pathOutputImage As String
    Public imgTrans As ImageTransform
    Public _inputImage As Image
    Private _inputImagePath As String

    Public Log As StringBuilder

    ReadOnly Property Height() As String
        Get
            Return _inputImage.Height
        End Get
    End Property

    ReadOnly Property GetLof() As String
        Get
            Return Log.ToString
        End Get
    End Property


    ReadOnly Property Width() As String
        Get
            Return _inputImage.Width
        End Get
    End Property

    Public Sub New(ByVal ImagePath As String)
        Try
            _inputImagePath = ImagePath
            _inputImage = Image.FromFile(_inputImagePath)
            _pathOutputImage = _inputImagePath
            Log = New StringBuilder()
        Catch er As Exception
            Throw er
        End Try
    End Sub

    Private Function getRandomName() As String
        Dim fi As New FileInfo(_inputImagePath)
        Return fi.DirectoryName & "\TNS_" & RndString() & fi.Extension
    End Function

    Public Function Transform(ByVal XMLFile As String)
        Dim reader As New System.Xml.Serialization.XmlSerializer(GetType(ImageTransform))
        Dim file As New System.IO.StreamReader(XMLFile)
        imgTrans = reader.Deserialize(file)
        file.Close()

        'resize
        If Not imgTrans.Resize.Height Is Nothing Then
            Resize(imgTrans.Resize.Height.ToString, imgTrans.Resize.Width.ToString)
        End If
        'crop
        If Not imgTrans.Crop.Height Is Nothing Then
            Crop(imgTrans.Crop.Height.ToString, imgTrans.Crop.Width.ToString)
        End If
        'rotate
        If Not imgTrans.Rotate.Degrees Is Nothing Then
            Rotate(imgTrans.Rotate.Degrees)
        End If
    End Function

    Public Function Crop(ByVal Height As String, ByVal Width As String)
        _pathOutputImage = getRandomName()
        Dim bmpImage As Bitmap
        Dim recCrop As Rectangle
        Dim bmpCrop As Bitmap
        Dim gphCrop As Graphics
        Dim recDest As Rectangle
        Try
            TakeNote("Crop " & Height & " x " & Width)
            bmpImage = New Bitmap(_inputImage)
            recCrop = New Rectangle(0, 0, Width, Height)
            bmpCrop = New Bitmap(recCrop.Width, recCrop.Height, bmpImage.PixelFormat)
            gphCrop = Graphics.FromImage(bmpCrop)
            recDest = New Rectangle(0, 0, Width, Height)
            gphCrop.DrawImage(bmpImage, recDest, recCrop.X, recCrop.Y, recCrop.Width, _
                recCrop.Height, GraphicsUnit.Pixel)

        Catch er As Exception
            TakeNote("CROP ERR: " & er.ToString)
            Throw er
        Finally
            bmpCrop.Save(_pathOutputImage)
            _inputImage = Image.FromFile(_pathOutputImage)
        End Try
    End Function

    Public Function Rotate(ByVal Flip As String)

        _pathOutputImage = getRandomName()
        TakeNote("Rotating : " & Flip)
        Dim thumb As System.Drawing.Image
        Try
            thumb = _inputImage
            Select Case Flip
                Case "90"
                    thumb.RotateFlip(RotateFlipType.Rotate90FlipXY)
                Case "180"
                    thumb.RotateFlip(RotateFlipType.Rotate180FlipXY)
                Case "270"
                    thumb.RotateFlip(RotateFlipType.Rotate270FlipXY)
            End Select
        Catch er As Exception
            TakeNote("ROTATE ERR: " & er.ToString)
            Throw

        Finally
            thumb.Save(_pathOutputImage)
            _inputImage = thumb
        End Try

    End Function

    Public Function Resize(ByVal Height As String, ByVal Width As String)
        _pathOutputImage = getRandomName()
        Dim thumb As System.Drawing.Image
        thumb = _inputImage
        Dim inp As New IntPtr()
        Dim fi As FileInfo
        Try
            TakeNote("Resize " & Height & " x " & Width)
            If Height > 0 And Width > 0 Then
                thumb = _inputImage.GetThumbnailImage(Height, Width, Nothing, inp)
            Else
                thumb = _inputImage
            End If
        Catch er As Exception
            TakeNote("RESIZE ERR: " & er.ToString)
            Throw er
        Finally
            thumb.Save(_pathOutputImage)
            _inputImage = thumb
        End Try
    End Function

    Public Function SaveImage() As String
        Log = Nothing
        Return _pathOutputImage
    End Function

    Private Sub TakeNote(ByVal str As String)
        Log.Append(str & vbCrLf)
    End Sub

    Private Function RndString(Optional ByVal sLen As Integer = 15) As String
        Dim r As String = ""
        Dim i As Integer
        Randomize()
        For i = 1 To sLen
            Randomize(Int((57 - 48 + 1) * Rnd() + 48))
            Randomize()
            If Int(2 * Rnd() + 1) = 1 Then
                r = r + Chr(Int((57 - 48 + 1) * Rnd() + 48))
            Else
                r = r + Chr(Int((90 - 65 + 1) * Rnd() + 65))
            End If
        Next i
        Return DateTime.Now.Year & DateTime.Now.Month & DateTime.Now.Day & r
    End Function
End Class

Take your pic of the two

Aeros
See if this is helpful, but it's in C#:

http://west-wind.com/weblog/posts/283.aspx
ASKER CERTIFIED SOLUTION
Avatar of AerosSaga
AerosSaga

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jtmerch

ASKER

Thank you all for your help.  Aeros, your instructions have been very helpful and I'll reward you the points.
Your very welcome my friend.

Aeros