Home > Enterprise >  asp.net check image resolution and save in DB
asp.net check image resolution and save in DB

Time:02-15

asp.net core MVC - framework net6.0

I have a page in which i upload an image and save it to the db. the file i'm getting from the view is IFormFile. I want to be able to check the resolution (width and height) of the photo before saving in DB. Can it be done with IFormFile?

here is the controller that handles the file :

public JsonResult Submit(IFormFile PhotoFile)
        {
            int success = 0;
            string excep = "";
            try
            {
                if (PhotoFile.Length > 0)
                {
                    using (var ms = new MemoryStream())
                    {
                        PhotoFile.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                    }
                }
                ApplicationUser appUser =
                     _unitOfWork.ApplicationUser.GetAll().Where(a => a.UserName == User.Identity.Name).FirstOrDefault();
                if (appUser != null)
                {
                    FileUpload fileUpload = new FileUpload()
                    {
                        file = PhotoFile,
                        CompanyId = appUser.CompanyId
                    };
                    SaveFile(fileUpload);
                }
                excep = "success";
                success = 1;
                return Json(new { excep, success });
            }
            catch (Exception ex)
            {
                excep = "fail";
                success = 0;
                return Json(new { excep, success });
            }   
        }
public string SaveFile(FileUpload fileObj)
        {
            Company company = _unitOfWork.Company.GetAll().
                Where(a => a.Id == fileObj.CompanyId).FirstOrDefault();
            if(company != null && fileObj.file.Length > 0)
            {
                using (var ms = new MemoryStream())
                {
                    fileObj.file.CopyTo(ms);
                    var fileBytes = ms.ToArray();
                    company.PhotoAd = fileBytes;
                    _unitOfWork.Company.Update(company);
                    _unitOfWork.Save();
                    return "Saved";
                }
            }
            return "Failed";
        }

CodePudding user response:

As far as I know this isn't possible with just IFormFile and you need System.Drawing.Common. So first you need to convert it like:

using var image = Image.FromStream(PhotoFile.OpenReadStream());

Then you can simply get the height/width with image.height and image.width

  • Related