asp.net core 图片转正

浪淘沙10个月前后端75

在 ASP.NET Core 中将图片旋转为正向,通常你需要处理图片的 EXIF 信息,因为一些相机和手机拍摄的照片会包含方向信息,表示照片应该如何旋转才能显示为正确的方向。可以使用一个图像处理库来实现这个功能,比如 ImageSharpSystem.Drawing.Common

下面是一个使用 ImageSharp 库来自动调整图像方向的示例:

  1. 首先,你需要安装 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 提供了很多操作方法,比如裁剪、缩放、添加水印等。


相关文章

asp.net core弹出对话框最佳实践

 public void OnGet()  {         ...

asp.net core 图片左下角 加水印

using SixLabors.Fonts; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Drawi...

asp.net core 取得页面form中所有表单值

public IActionResult OnPostSubmit()         { &n...

ubuntu 删除asp.net core 8.0

1. 查找已安装的 ASP.NET Core 8.0 版本dotnet --list-runtimes dotnet --list-sdks2. 删除 ASP.NET Core...

SqlSugar

   var dt = _db.SqlQueryable<object>("select * fr...

asp.net core 发送模板消息

 private readonly HttpClient _httpClient;  public testModel(HttpCli...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。