如何用ImageSharp实现Image<Rgba32>转Byte[]及基于EXIF方向获取旋转翻转模式
嘿,我来帮你搞定这两个ImageSharp的问题:
1. 将Image转换为Byte[]
要把Image<Rgba32>转成byte[],最常用的方法是借助MemoryStream,把图片写入流之后再转成字节数组。这里给你个实用的代码示例:
using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using System.IO; public byte[] ConvertImageToByteArray(Image<Rgba32> image) { // 用using自动释放流资源,避免内存泄漏 using var memoryStream = new MemoryStream(); // 根据需求选择保存格式:SaveAsPng、SaveAsJpeg、SaveAsWebp都可以 image.SaveAsPng(memoryStream); // 如果需要定制编码参数(比如JPEG质量),可以传编码器选项: // var jpegOpts = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoderOptions { Quality = 90 }; // image.SaveAsJpeg(memoryStream, jpegOpts); return memoryStream.ToArray(); }
注意:一定要用using包裹MemoryStream,确保资源能被正确释放;另外选择保存格式时,要和你的业务需求匹配——比如如果是照片,用JPEG更省空间;如果需要透明通道,就选PNG。
2. 根据EXIF Orientation获取对应的RotateMode和FlipMode
ImageSharp完全支持处理EXIF的Orientation信息,甚至提供了一键处理的方法。如果你需要手动映射对应的旋转/翻转模式,也很容易实现:
方法一:自动处理(推荐)
直接调用AutoOrient()方法,它会自动读取EXIF中的Orientation标签,调整图片到正确方向,同时移除这个标签(避免后续重复处理):
using var image = Image.Load<Rgba32>("your-image-file.jpg"); image.AutoOrient(); // 一步搞定,省心省力
方法二:手动映射RotateMode和FlipMode
如果你需要自己获取对应的模式,可以先读取EXIF的Orientation值,再做映射:
using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Metadata.Profiles.Exif; using SixLabors.ImageSharp.Processing; // 加载图片并读取EXIF using var image = Image.Load<Rgba32>("your-image-file.jpg"); var exifProfile = image.Metadata.ExifProfile; if (exifProfile != null) { var orientationValue = exifProfile.GetValue(ExifTag.Orientation); if (orientationValue != null) { var orientation = (Orientation)orientationValue.Value; var (rotateMode, flipMode) = GetRotationAndFlip(orientation); // 应用旋转和翻转到图片上 image.Mutate(x => x.RotateFlip(rotateMode, flipMode)); } } // 映射Orientation到RotateMode和FlipMode的方法 private (RotateMode Rotate, FlipMode Flip) GetRotationAndFlip(Orientation orientation) { return orientation switch { Orientation.Normal => (RotateMode.None, FlipMode.None), Orientation.FlipHorizontal => (RotateMode.None, FlipMode.Horizontal), Orientation.Rotate180 => (RotateMode.Rotate180, FlipMode.None), Orientation.FlipVertical => (RotateMode.None, FlipMode.Vertical), Orientation.FlipHorizontalRotate270 => (RotateMode.Rotate270, FlipMode.Horizontal), Orientation.Rotate90 => (RotateMode.Rotate90, FlipMode.None), Orientation.FlipHorizontalRotate90 => (RotateMode.Rotate90, FlipMode.Horizontal), Orientation.Rotate270 => (RotateMode.Rotate270, FlipMode.None), _ => (RotateMode.None, FlipMode.None) // 处理未知值 }; }
这个映射逻辑完全对应EXIF Orientation的标准定义,覆盖了所有可能的取值。
内容的提问来源于stack exchange,提问作者dudedev
相关产品推荐
相关产品推荐

