asp.net core 图片转正

浪淘沙1年前后端126

在 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 razor加载模板文件路径

  var templateContent = "${include(\"" + App.HostE...

asp.net core 获取url及参数

  var url = $"{Request.Scheme}://{Request.Host}{Request.Path}{Request....

_LayoutAdmin.cshtml 取得url,调用ViewComponent 视图

_LayoutAdmin.cshtml 取得url,调用ViewComponent 视图

<body id="watermark-parent"> @{ var name = Furion.App.HttpC...

asp.net core return Content 返回可解析的html

return Content(     "<!DOCTYPE html><html><body&g...

普能html页面post到 cshtml页面,出现400错误解决方法

  [IgnoreAntiforgeryToken]  public class keywordsModel : PageModel  {    &n...

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

public IActionResult OnPostSubmit()         { &n...

发表评论    

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