Mathematics
Mathematics

Reputation: 7628

how can I get image size (w x h) using Stream

I have this code i am using to read uploaded file, but i need to get size of image instead but not sure what code can i use

HttpFileCollection collection = _context.Request.Files;
            for (int i = 0; i < collection.Count; i++)
            {
                HttpPostedFile postedFile = collection[i];

                Stream fileStream = postedFile.InputStream;
                fileStream.Position = 0;
                byte[] fileContents = new byte[postedFile.ContentLength];
                fileStream.Read(fileContents, 0, postedFile.ContentLength);

I can get the file right but how to check it's image (width and size) sir ?

Upvotes: 24

Views: 36335

Answers (3)

Mukund Thakkar
Mukund Thakkar

Reputation: 1305

HttpPostedFile file = null;
file = Request.Files[0]

if (file != null && file.ContentLength > 0)
{
    System.IO.Stream fileStream = file.InputStream;
    fileStream.Position = 0;

    byte[] fileContents = new byte[file.ContentLength];
    fileStream.Read(fileContents, 0, file.ContentLength);

    System.Drawing.Image image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(fileContents));
    image.Height.ToString(); 
}

Upvotes: 4

Rob
Rob

Reputation: 3574

First you have to write the image:

System.Drawing.Image image = System.Drawing.Image.FromStream (new System.IO.MemoryStream(byteArrayHere));

and afterwards you have the :

image.Height.ToString(); 

and the

image.Width.ToString();

note: you might want to add a check to be sure it's an image that was uploaded?

Upvotes: 52

Thorsten Westheider
Thorsten Westheider

Reputation: 10932

Read the image into a buffer (you either have a Stream to read from or the byte[], because if you had the Image you'd have the dimensions anyway).

public Size GetSize(byte[] bytes)
{
   using (var stream = new MemoryStream(bytes))
   {
      var image = System.Drawing.Image.FromStream(stream);

      return image.Size;
   }
}

You can then go ahead and get the image dimensions:

var size = GetSize(bytes);

var width = size.Width;
var height = size.Height;

Upvotes: 3

Related Questions