检查上传图片的尺寸

发布于 2024-10-20 12:45:57 字数 139 浏览 8 评论 0原文

我在我的网站上使用 asp.net 3.5 和 c#。这是我的问题:

我的页面上有一个上传按钮和 asp:Image。用户可以从他的计算机上传图像,该图像将显示在 asp:image 中。但在显示图像之前,我想检查上传图像的宽度和高度。我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

遮云壑 2024-10-27 12:45:57
    Image img = System.Drawing.Image.FromFile("test.jpg");
    int width = img.Width;
    int height = img.Height;

您可能需要添加 System.Drawing 引用。

如果您尚未将图像保存到磁盘,您也可以使用 FromStream 函数,但看看您如何使用图像(用户可以在图像控件中查看),我怀疑它已经打开磁盘。流到图像可能比磁盘到图像快,也可能不快。您可能需要进行一些分析以查看哪个具有更好的性能。

    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.

旧情勿念 2024-10-27 12:45:57

在 ASP.NET 中,上传文件时通常会使用 byte[] 或 Stream。下面,我向您展示一种方法,其中 bytes 是上传文件的 byte[]。如果您首先保存文件,那么您就有了一个物理文件。您可以使用@Jakob 或@Fun Mun Pieng 向您展示的内容。

无论哪种方式,请务必像我在此处所示的那样处理您的 Image 实例。这非常重要(其他人没有展示这一点)。

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

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;
    }
  }
浸婚纱 2024-10-27 12:45:57

请尝试以下操作:

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

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);
    }
}
皓月长歌 2024-10-27 12:45:57

将图像加载到 图像 并检查服务器端的尺寸?

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

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...
以歌曲疗慰 2024-10-27 12:45:57

试试这个:

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:

Stream ipStream = fuAttachment.PostedFile.InputStream;
using (var image = System.Drawing.Image.FromStream(ipStream))
{                    
    float w = image.PhysicalDimension.Width;
    float h = image.PhysicalDimension.Height;
}
街角迷惘 2024-10-27 12:45:57

试试这个。

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

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

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

使用:

if ( CheckImgDimensions("~/Content/img/MyPic.jpg",128,128) ){ 
     /// what u want
  }

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
  }
温柔戏命师 2024-10-27 12:45:57

这就是我检查控制器 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);
    }
}

在此处输入图像描述
输入图片此处描述
我希望这可以帮助遇到这个问题的其他人。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文