C#中Excel插入Base64图片自动旋转问题求助
解决C#向Excel添加Base64图片时的自动旋转问题
问题根源
部分图片自动旋转是因为图片包含Exif方向标签,但你用new Bitmap(stream)加载Base64转成的流时,.NET默认会丢弃部分元数据(导致PropertyItems为空),同时Excel会读取图片残留的Exif标签再次旋转,或者Bitmap加载时已自动应用旋转但Excel重复处理,最终导致显示异常。
解决方案
核心是正确保留图片元数据、手动处理Exif方向并移除标签,避免Excel重复旋转。
步骤1:修复Base64转Image时的元数据读取
不要用new Bitmap(stream)加载图片,改用Image.FromStream并启用元数据保留:
byte[] imageBytes = Convert.FromBase64String(base64Image); using (MemoryStream ms = new MemoryStream(imageBytes)) { // 第二个参数启用颜色管理,第三个参数验证图片数据,确保保留Exif元数据 Image image = Image.FromStream(ms, true, true); // 后续处理逻辑... }
步骤2:读取并处理Exif方向标签
Exif方向标签的ID为0x0112,根据标签值旋转图片后,移除该标签防止Excel再次处理:
public static Image FixImageOrientation(string base64Image) { byte[] imageBytes = Convert.FromBase64String(base64Image); using (MemoryStream ms = new MemoryStream(imageBytes)) { Image image = Image.FromStream(ms, true, true); const int exifOrientationId = 0x0112; // 查找方向标签 PropertyItem orientationItem = image.PropertyItems.FirstOrDefault(p => p.Id == exifOrientationId); if (orientationItem != null) { short orientationValue = BitConverter.ToInt16(orientationItem.Value, 0); RotateFlipType rotateType = orientationValue switch { 1 => RotateFlipType.RotateNoneFlipNone, 2 => RotateFlipType.RotateNoneFlipX, 3 => RotateFlipType.Rotate180FlipNone, 4 => RotateFlipType.Rotate180FlipX, 5 => RotateFlipType.Rotate90FlipX, 6 => RotateFlipType.Rotate90FlipNone, 7 => RotateFlipType.Rotate270FlipX, 8 => RotateFlipType.Rotate270FlipNone, _ => RotateFlipType.RotateNoneFlipNone }; // 旋转图片 image.RotateFlip(rotateType); // 移除方向标签,避免Excel重复旋转 image.RemovePropertyItem(exifOrientationId); } // 返回处理后的图片(复制为Bitmap避免原Image因流释放失效) return new Bitmap(image); } }
步骤3:将处理后的图片插入Excel
使用处理后的Image对象插入Excel,此时图片已按正确方向显示,且无残留Exif标签导致重复旋转:
// 示例:使用EPPlus插入图片 using (ExcelPackage package = new ExcelPackage(new FileInfo("output.xlsx"))) { ExcelWorksheet worksheet = package.Workbook.Worksheets.First(); Image fixedImage = FixImageOrientation(yourBase64String); worksheet.Drawings.AddPicture("FixedImage", fixedImage); package.Save(); }
关键说明
- 之前调用
image.RotateFlip(RotateFlipType.RotateNoneFlipNone)无效,是因为Bitmap加载时可能已自动应用Exif旋转,且未移除方向标签,Excel仍会读取标签再次旋转。 - 必须移除Exif方向标签,否则Excel会根据标签值再次调整图片方向,导致显示异常。
内容的提问来源于stack exchange,提问作者deanpillow
相关产品推荐
相关产品推荐

