如何使用Stream获取图像大小(wxh)

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

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

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

首先你必须写下图像:

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

然后你有:

 image.Height.ToString(); 

 image.Width.ToString(); 

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

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

将图像读入缓冲区(要么有一个Stream要读取,要么是字节[],因为如果你有图像,那么无论如何你都有尺寸)。

 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;