asp.net检查图像分辨率并保存在数据库中



asp.net核心MVC-框架net6.0

我有一个页面,在其中我上传了一个图像并将其保存到数据库。我从视图中得到的文件是IFormFile。我希望能够在保存到DB之前检查照片的分辨率(宽度和高度(。可以用IFormFile完成吗?

这是处理文件的控制器:

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

据我所知,仅使用IFormFile是不可能的,您需要System.Drawing.Common。因此,首先你需要将其转换为:

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

然后你可以简单地用image.heightimage.width获得高度/宽度

最新更新