如何使用Stream获取图像大小(宽x高)

24

我有这段代码,用于读取上传的文件,但我需要获取图像的尺寸,不确定可以使用什么代码。

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

我可以正确获取文件,但是如何检查它的图像尺寸(宽度和大小)呢?

3个回答

51

首先你需要编写图片:

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

之后你会有:

image.Height.ToString(); 

image.Width.ToString();

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


18
嘿,在 "using" 子句中添加那个! - Lilith River

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

3

将图像读入缓冲区(您可以从流中读取或使用byte[],因为如果您拥有图像,则无论如何都会拥有尺寸)。


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

      return image.Size;
   }
}

然后您可以继续获取图像尺寸:

var size = GetSize(bytes);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接