asp.net core 图片转正
在 ASP.NET Core 中将图片旋转为正向,通常你需要处理图片的 EXIF 信息,因为一些相机和手机拍摄的照片会包含方向信息,表示照片应该如何旋转才能显示为正确的方向。可以使用一个图像处理库来实现这个功能,比如 ImageSharp 或 System.Drawing.Common。
下面是一个使用 ImageSharp 库来自动调整图像方向的示例:
首先,你需要安装
ImageSharp包:
dotnet add package SixLabors.ImageSharp
2、然后,可以创建一个方法来加载图片,检查其方向,并根据需要旋转它:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using System.IO;
public class ImageService
{
public async Task RotateImageToCorrectOrientationAsync(string inputFilePath, string outputFilePath)
{
using (var image = await Image.LoadAsync(inputFilePath))
{
var exifProfile = image.Metadata.ExifProfile;
if (exifProfile != null)
{
var orientation = exifProfile.GetValue(ExifTag.Orientation);
if (orientation != null)
{
switch (orientation.Value)
{
case 1: // Normal
break;
case 3: // 180 degrees
image.Mutate(x => x.Rotate(180));
break;
case 6: // 90 degrees clockwise
image.Mutate(x => x.Rotate(90));
break;
case 8: // 90 degrees counter-clockwise
image.Mutate(x => x.Rotate(-90));
break;
}
}
}
await image.SaveAsync(outputFilePath);
}
}
}这段代码会读取图片,检查它的 EXIF 数据中的方向标记,并根据标记进行相应的旋转。
使用方法:
var imageService = new ImageService();
await imageService.RotateImageToCorrectOrientationAsync("input.jpg", "output.jpg");这样,你就能根据图片的方向信息来自动调整图片为正向显示。
如果你需要其他图像处理功能,ImageSharp 提供了很多操作方法,比如裁剪、缩放、添加水印等。