加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用aspnetcore web api中的图像的EXIF数据旋转/翻转图像

发布时间:2020-12-16 01:26:35 所属栏目:百科 来源:网络整理
导读:我有一个网络应用程序,用户可以通过手机直接拍照来上传个人资料图片.由于图像的EXIF方向,前端必须在显示图像之前变换图像(旋转/翻转).但是,我想在保存图片之前在后端执行转换以避免前端的转换.后端是用c#编写的.net core 2.0应用程序. 有没有人有关于可用于
我有一个网络应用程序,用户可以通过手机直接拍照来上传个人资料图片.由于图像的EXIF方向,前端必须在显示图像之前变换图像(旋转/翻转).但是,我想在保存图片之前在后端执行转换以避免前端的转换.后端是用c#编写的.net core 2.0应用程序.

有没有人有关于可用于访问EXIF数据并进行转换的库的建议.

截至目前,我已经找到了https://github.com/SixLabors/ImageSharp,并查看了如何使用它的文档.

解决方法

最后,我使用了ImageSharp库.它可能对其他人有帮助.

private byte[] TransformAvatarIfNeeded(byte[] imageInBytes)
    {
        using (var image = Image.Load(imageInBytes))
        {
            ExifValue exifOrientation = image.MetaData?.ExifProfile?.GetValue(ExifTag.Orientation);

            if (exifOrientation == null) return imageInBytes;

            RotateMode rotateMode;
            FlipMode flipMode;
            SetRotateFlipMode(exifOrientation,out rotateMode,out flipMode);

            image.Mutate(x => x.RotateFlip(rotateMode,flipMode));
            image.MetaData.ExifProfile.SetValue(ExifTag.Orientation,(ushort)1);

            var imageFormat = Image.DetectFormat(imageInBytes);

            return ImageToByteArray(image,imageFormat);
        }
    }

    private byte[] ImageToByteArray(Image<Rgba32> image,IImageFormat imageFormat)
    {
        using (var ms = new MemoryStream())
        {
            image.Save(ms,imageFormat);
            return ms.ToArray();
        }
    }

    private void SetRotateFlipMode(ExifValue exifOrientation,out RotateMode rotateMode,out FlipMode flipMode)
    {
        var orientation = exifOrientation.Value.ToString();

        switch (orientation)
        {
            case "2":
                rotateMode = RotateMode.None;
                flipMode = FlipMode.Horizontal;
                break;
            case "3":
                rotateMode = RotateMode.Rotate180;
                flipMode = FlipMode.None;
                break;
            case "4":
                rotateMode = RotateMode.Rotate180;
                flipMode = FlipMode.Horizontal;
                break;
            case "5":
                rotateMode = RotateMode.Rotate90;
                flipMode = FlipMode.Horizontal;
                break;
            case "6":
                rotateMode = RotateMode.Rotate90;
                flipMode = FlipMode.None;
                break;
            case "7":
                rotateMode = RotateMode.Rotate90;
                flipMode = FlipMode.Vertical;
                break;
            case "8":
                rotateMode = RotateMode.Rotate270;
                flipMode = FlipMode.None;
                break;
            default:
                rotateMode = RotateMode.None;
                flipMode = FlipMode.None;
                break;
        }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读