Check uploaded image's dimensions

余生颓废 提交于 2019-11-28 09:14:54
    Image img = System.Drawing.Image.FromFile("test.jpg");
    int width = img.Width;
    int height = img.Height;

You may need to add the System.Drawing reference.

You may also use the FromStream function if you have not saved the image to disk yet, but looking at how you're using the image (viewable by user in an Image control), I suspect it's already on disk. Stream to image may or may not be faster than disk to image. You might want to do some profiling to see which has better performance.

In ASP.NET you typically have the byte[] or the Stream when a file is uploaded. Below, I show you one way to do this where bytes is the byte[] of the file uploaded. If you're saving the file fisrt then you have a physical file. and you can use what @Jakob or @Fun Mun Pieng have shown you.

Either ways, be SURE to dispose your Image instance like I've shown here. That's very important (the others have not shown this).

  using (Stream memStream = new MemoryStream(bytes))
  {
    using (Image img = System.Drawing.Image.FromStream(memStream))
    {
      int width = img.Width;
      int height = img.Height;
    }
  }
AquaticLyf

Try the following:

public bool ValidateFileDimensions()
{
    using(System.Drawing.Image myImage =
           System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream))
    {
        return (myImage.Height == 140 && myImage.Width == 140);
    }
}

Load the image into an Image and check the dimensions serverside?

Image uploadedImage = Image.FromFile("uploadedimage.jpg");
// uploadedImage.Width and uploadedImage.Height will have the dimensions...
Khaled Tarboosh

Try this:

Stream ipStream = fuAttachment.PostedFile.InputStream;
using (var image = System.Drawing.Image.FromStream(ipStream))
{                    
    float w = image.PhysicalDimension.Width;
    float h = image.PhysicalDimension.Height;
}

Try this.

              public boolean CheckImgDimensions(string imgPath, int ValidWidth , int ValidHeight){  

                 var img = Image.FromFile(Server.MapPath(imgPath));

                 return (img.width == ValidWidth &&  img.height == ValidHeight );
                }

Use:

if ( CheckImgDimensions("~/Content/img/MyPic.jpg",128,128) ){ 
     /// what u want
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!