C# 获取上传图像的纵横比(宽度和高度)
我想在API中验证我的图像上载。我只想允许在横向模式的照片。我还想检查纵横比。这是我检查文件是否为图像的代码:C# 获取上传图像的纵横比(宽度和高度),c#,asp.net-core-2.0,asp.net-core-webapi,C#,Asp.net Core 2.0,Asp.net Core Webapi,我想在API中验证我的图像上载。我只想允许在横向模式的照片。我还想检查纵横比。这是我检查文件是否为图像的代码: [HttpPost] public JsonResult Post(IFormFile file) { if (file.ContentType.ToLower() != "image/jpeg" && file.ContentType.ToLower() != "image/jpg" &&
[HttpPost]
public JsonResult Post(IFormFile file)
{
if (file.ContentType.ToLower() != "image/jpeg" &&
file.ContentType.ToLower() != "image/jpg" &&
file.ContentType.ToLower() != "image/png")
{
// not a .jpg or .png file
return new JsonResult(new
{
success = false
});
}
// todo: check aspect ratio for landscape mode
return new JsonResult(new
{
success = true
});
}
由于System.Drawing.Image
不再可用,我无法找到方法将iFormFile转换为图像类型的对象,检查宽度和高度以计算其纵横比。如何在ASP.NET Core API 2.0中获取类型为iFormFile的图像的宽度和高度
由于System.Drawing.Image
不再可用,我无法找到方法将iFormFile转换为图像类型的对象,检查宽度和高度以计算其纵横比
这实际上是不对的。微软已经发布了System.Drawing.Common
,它提供了跨平台的GDI+图形功能。API应该是任何旧系统的就地替代品。图纸代码:
using (var image = Image.FromStream(file.OpenReadStream()))
{
// use image.Width and image.Height
}
我在.net core中遇到了类似的问题,我通过客户端解决方案解决了这个问题。根据您的项目条件,您可以信任客户端处理,并让他们做一些工作。您可以通过一些js代码行获得纵横比,这些代码行是,然后将这些(width
&height
)传递给API:
var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.src = this.result as string;
image.addEventListener('load', function () {
console.log(`height: ${this.height}, width: ${this.width}`);
});
}, false);
reader.readAsDataURL(file);
}
API将如下所示:
//POST : api/samples?width=100&height=500
[HttpPost]
public JsonResult Post(IFormFile file, int width, int height) {}
我已经测试了此解决方案的多文件上传功能,效果很好。您不应该仅仅为了获取文件的尺寸而渲染文件,而应该使用像SoftImaging这样的图像库从文件中提取尺寸。@DourHighArch您不应该仅仅为了获取文件的尺寸而渲染文件-这可能是正确的,但是使用第三方库只是对图像进行简单的尺寸检查我不认为这是个好办法。谢谢你,我不知道它被搬到了一个裸体包里。它起作用了!nuget包有外部依赖性:是的,不是。System.Drawing是一个GDI+图形库,所以您显然需要这些组件。该链接所解决的问题是针对运行精简操作系统映像的容器,因此,是的,您必须在那里安装组件。