chuckyCheese
chuckyCheese

Reputation: 369

Check uploaded image's dimensions

I'm using asp.net 3.5 and c# on my web site. Here is my question:

I have an upload button and asp:Image on a page. An user can upload an image from his computer and that image will be displayed in the asp:image. But before I display the image, I would like to check the width and height of the uploaded image. How do I do this?

Upvotes: 12

Views: 31717

Answers (7)

NMeneses
NMeneses

Reputation: 172

This is how I do my checking in the Controller ActionResult:

public ActionResult ThumbnailUpload(HttpPostedFileBase image, PressRelease pr)
{
    var id = pr.Id;
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    PressRelease pressRelease = db.PressReleases.Find(id);
    if (pressRelease == null)
    {
        return HttpNotFound();
    }
    bool success = false;
    var imgName = "";
    var path = "";
    ViewBag.Message = "";
    try
    {
        //Check for uploaded file
        //You can set max file upload size in your Web.config file
        if (image.ContentLength > 0)
        {                   
            //Check the uploaded file is of the type needed/required
            if (Path.GetExtension(image.FileName) == ".jpg")
            {
                //Get the uploaded file from HttpPostedFileBase
                System.IO.Stream stream = image.InputStream;

                //Convert the uploaded file to Image
                System.Drawing.Image img = System.Drawing.Image.FromStream(stream);

                //Get the Width and Height of the uploaded file
                int width = img.Width;
                int height = img.Height;

                //Check the Width & Height are the dimensions you want
                if (width != 150 && height != 175)
                {
                    //If the Width & Height do not meet your specifications, write a message to the user
                    success = false;
                    ViewBag.Message = "Thumbnail upload failed.";
                    ViewBag.Exception = "Image dimensions must 150w by 175h.";

                    //Return the view with the Model so error messages get displayed
                    return View("UploadImages", pressRelease);
                }
                else
                {
                    //If Width & Height meet your specs, continue with uploading and saving the image
                    imgName = Path.GetFileName(image.FileName);
                    path = Path.Combine(Server.MapPath("...Your File Path..."), imgName);
                    image.SaveAs(path);
                    success = true;
                    ViewBag.Success = success;
                    ViewBag.Message = "Thumbnail uploaded successfully.";
                    pressRelease.ThumbName = Path.GetFileNameWithoutExtension(image.FileName);
                    TryUpdateModel(pressRelease);
                    db.SaveChanges();
                }
            }
            else if(Path.GetExtension(image.FileName) != ".jpg")
            {
                //If the uploaded file is not of the type needed write message to user
                success = false;
                ViewBag.Message = "Thumbnail upload failed.";
                ViewBag.Exception = "Uploaded file must have '.jpg' as the file extension.";
                return View("UploadImages", pressRelease);
            }
        }
        return View("UploadImages", pressRelease);
    }
    catch (Exception ex)
    {
        ViewBag.Success = success;
        ViewBag.Exception = ex.Message;
        ViewBag.Message = "Thumbnail upload failed.";
        return View("UploadImages", pressRelease);
    }
}

enter image description here enter image description here I hope this helps someone else who runs in to this problem.

Upvotes: 0

Ad Kahn
Ad Kahn

Reputation: 579

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
  }

Upvotes: 0

Khaled Tarboosh
Khaled Tarboosh

Reputation: 31

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

Upvotes: 1

AquaticLyf
AquaticLyf

Reputation: 81

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

Upvotes: 8

Shiv Kumar
Shiv Kumar

Reputation: 9799

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

Upvotes: 14

Fun Mun Pieng
Fun Mun Pieng

Reputation: 6891

    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.

Upvotes: 24

Jakob Gade
Jakob Gade

Reputation: 12419

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

Upvotes: 3

Related Questions