如何使用Stream获取图像大小(w x h)

时间:2013-05-20 13:23:06

标签: c# asp.net image file stream

我有这个代码,我用来读取上传的文件,但我需要获取图像的大小,但不知道我可以使用什么代码

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);

我可以正确地获取文件但是如何检查它的图像(宽度和大小)先生?

2 个答案:

答案 0 :(得分:36)

首先你必须写下图像:

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

然后你有了:

image.Height.ToString(); 

image.Width.ToString();

注意:您可能需要添加一项检查,以确保它是上传的图片?

答案 1 :(得分:4)

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(); 
}