How do you convert a HttpPostedFileBase to an Image?

后端 未结 2 1438
刺人心
刺人心 2020-12-04 10:08

I am using ASP.NET MVC and I\'ve an action that uploads the file. The file is being uploaded properly. But I want width and height of the image. I think I need to convert th

2条回答
  •  臣服心动
    2020-12-04 10:32

    If you are sure, that the source is image and doesn't need editing, you can do it easily as described here

    [HttpPost]
    public void Index(HttpPostedFileBase file)
    {
        if (file.ContentLength > 0)
        {
            var filename = Path.GetFileName(file.FileName);
    
            System.Drawing.Image sourceimage =
                System.Drawing.Image.FromStream(file.InputStream);
        }
    }
    

    To secure the file is image, add javascript validation to View by adding accept attribute with MIME type to input tag

    
    

    and jQuery validation script

    $.validator.addMethod('accept', function () { return true; });
    

    The whole solution can be found here

提交回复
热议问题