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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16650552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:33:47  来源:igfitidea点击:

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

c#asp.netimagefilestream

提问by Mathematics

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 ?

我可以得到正确的文件,但如何检查它的图像(宽度和大小)先生?

采纳答案by Rob

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?

注意:您可能想添加一个检查以确保它是上传的图像?

回答by Mukund

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

回答by Thorsten Westheider

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

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

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;