Get dimensions (Height and Width) of an uploaded image in ASP.Net using C#

Last Reply on Nov 20, 2014 06:14 AM By Mudassar

Posted on Nov 19, 2014 03:06 AM

I have the following code:

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.IO.Path
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Drawing
Imports System.Drawing.Bitmap
Imports System.Drawing.Imaging
Imports System.Web.UI.WebControls.WebControl
Imports System.Web.UI.WebControls.FileUpload


Partial Class wwwroot_Portals_Sales_Upload_VB
    Inherits System.Web.UI.Page

    Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
        Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
        Dim con As New SqlConnection(strConnString)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            Return True
        Catch ex As Exception
            Response.Write(ex.Message)
            Return False
        Finally
            con.Close()
            con.Dispose()
        End Try
    End Function

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

        ' Read the file and convert it to Byte Array 
        Dim filePath As String = FileUpload1.PostedFile.FileName
        Dim filename As String = Path.GetFileName(filePath)
        Dim ext As String = Path.GetExtension(filename)
        Dim contenttype As String = String.Empty
        Dim fileSize = (FileUpload1.PostedFile.ContentLength) / 1024

        'Limits max file upload kb'''''''''''''''''''''''''''
        Dim msg As String
        Const upload_max_size = 25  'Adjust max kb here
        Dim fileFld = Request.Files(0)
        Dim Size = fileFld.ContentLength
        If fileFld.ContentLength > upload_max_size * 1024 Then
            lblSize.Text = "<br/>Sorry, the image must be less than " & upload_max_size & "Kb"
        Else
            'Limits max file upload kb'''''''''''''''''''''''''''





            'When this code is added the image does not display
            'Dim stream As System.IO.Stream = FileUpload1.PostedFile.InputStream
            'Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(stream)

            'Dim height As Integer = image.Height
            'Dim width As Integer = image.Width





            'Set the contenttype based on File Extension
            Select Case ext
                
                Case ".jpeg"
                    contenttype = "image/jpeg"
                    Exit Select
                Case ".jpg"
                    contenttype = "image/jpg"
                    Exit Select
                Case ".png"
                    contenttype = "image/png"
                    Exit Select
                Case ".gif"
                    contenttype = "image/gif"
                    Exit Select
                    
            End Select
            If contenttype <> String.Empty Then

                Dim fs As Stream = FileUpload1.PostedFile.InputStream
                Dim br As New BinaryReader(fs)
                Dim bytes As Byte() = br.ReadBytes(fs.Length)
                Dim portalID As Integer = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId

                'insert the file into database 
                Dim strQuery As String = "insert into dbo.Sales (Name, ContentType, Data, Mall, Expiry, SaleDescription, PortalId) values (@Name, @ContentType, @Data, @Mall, @Expiry, @SaleDescription, @PortalId)"
                Dim cmd As New SqlCommand(strQuery)
                cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
                cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype
                cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
                cmd.Parameters.Add("@Mall", SqlDbType.Text).Value = mall.text
                cmd.Parameters.Add("@Expiry", SqlDbType.Text).Value = expiry.text
                cmd.Parameters.Add("@SaleDescription", SqlDbType.VarChar).Value = description.text
                cmd.Parameters.Add("@PortalId", SqlDbType.Int).Value = portalID


                InsertUpdateData(cmd)

                lblMessage.ForeColor = System.Drawing.Color.Green
                lblMessage.Text = "<br/>File Uploaded Successfully<br/>"
                lblsize.ForeColor = System.Drawing.Color.Red
                lblsize.Text = "<br/>File Size: " & Size.ToString

                lblErrorMessage.BackColor = Color.Red
                lblErrorMessage.ForeColor = Color.Black
                'lblErrorMessage.Text = "File size not to exceed 500x500 px"

                description.Text = String.Empty
                mall.Text = String.Empty
                expiry.Text = String.Empty

            Else
                lblMessage.ForeColor = System.Drawing.Color.Red
                lblMessage.Text = "File format not recognised." _
                & " Upload jpg, jpeg, png or pdf formats"
            End If

        End If
    End Sub

End Class

About halfway down you'll see this line:
'When this code is added the image does not display.

This file allows me to upload an image, along with some other fields into a db.
Works great and I can limit the size.

However I would also like to at least limit the dimensions of the image as well.

I've spent hours on this and have found lots of different ways of getting the job done.
But it all comes back to the same thing...the image just won't display.

The db shows binarydata in the appropriate field yet nothing displays.

When I use the commented out code, the upload still works and I get the dimension data of the image.
But again, the image just don't wanna show itself.

Any help is very much appreciated.

Thanks
Bob

You are viewing reply posted by: Mudassar on Nov 20, 2014 06:14 AM.
Posted on Nov 20, 2014 06:14 AM

To get the image Dimensions from FileUpload directly. Kindly do this way.

HTML

<asp:FileUpload ID = "FileUpload1" runat = "server" />
<asp:Button ID = "btnUpload" Text="Upload" runat="server" OnClick = "Upload" />

Code

protected void Upload(object sender, EventArgs e)
{
    System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
    int height = img.Height;
    int width = img.Width;
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Height: " + height + "\\nWidth: " + width +  "');", true);
}