System.Drawing.Image获取竖屏图片宽高颠倒问题求助
解决System.Drawing.Image获取竖屏图片宽高颠倒的问题
嘿,这个问题我之前也踩过坑!原因其实是你的图片带有EXIF方向元数据——System.Drawing.Image默认会读取这个标记并“逻辑上”旋转图片,但返回的Width和Height是旋转后的显示尺寸,而不是图片原始的像素宽高。
下面给你两种解决方案,按需选择:
方法一:直接获取实际宽高(不调整图片)
如果只是想拿到正确的宽高数值,不需要修改图片本身,可以先读取EXIF方向属性,再判断实际尺寸:
步骤1:编写获取EXIF方向的辅助方法
public static int GetExifOrientation(System.Drawing.Image image) { const int ExifOrientationPropertyId = 0x0112; // 对应EXIF的Orientation字段 if (image.PropertyIdList.Contains(ExifOrientationPropertyId)) { var propertyItem = image.GetPropertyItem(ExifOrientationPropertyId); // 方向值是16位整数,从Value数组的第0位读取 return BitConverter.ToInt16(propertyItem.Value, 0); } // 默认返回1,表示正常方向 return 1; }
步骤2:根据方向计算实际宽高
string OriginalFileLocation = "你的图片路径"; using (var fileStream = new FileStream(OriginalFileLocation, FileMode.Open)) using (var sourceImage = System.Drawing.Image.FromStream(fileStream)) { int orientation = GetExifOrientation(sourceImage); int actualWidth, actualHeight; // 当方向是6(顺时针90度)或8(逆时针90度)时,宽高会颠倒 switch (orientation) { case 6: case 8: actualWidth = sourceImage.Height; actualHeight = sourceImage.Width; break; default: actualWidth = sourceImage.Width; actualHeight = sourceImage.Height; break; } Console.WriteLine($"图片实际宽度: {actualWidth}, 实际高度: {actualHeight}"); }
方法二:修正图片方向后获取正确尺寸
如果需要后续对图片进行处理(比如裁剪、保存),建议直接把图片旋转到正确方向,这样Width和Height就会直接返回正确值:
步骤1:编写修正图片方向的辅助方法
public static System.Drawing.Image FixImageOrientation(System.Drawing.Image image) { int orientation = GetExifOrientation(image); if (orientation == 1) { // 方向正常,无需修改 return image; } // 根据不同的方向值,选择对应的旋转翻转类型 var rotateFlipType = orientation switch { 2 => RotateFlipType.RotateNoneFlipX, // 水平翻转 3 => RotateFlipType.Rotate180FlipNone, // 旋转180度 4 => RotateFlipType.Rotate180FlipX, // 旋转180度+水平翻转 5 => RotateFlipType.Rotate90FlipX, // 顺时针90度+水平翻转 6 => RotateFlipType.Rotate90FlipNone, // 顺时针90度(竖屏转横屏显示的常见情况) 7 => RotateFlipType.Rotate270FlipX, // 逆时针90度+水平翻转 8 => RotateFlipType.Rotate270FlipNone, // 逆时针90度 _ => RotateFlipType.RotateNoneFlipNone }; // 执行旋转翻转 image.RotateFlip(rotateFlipType); // 移除EXIF方向属性,避免后续处理重复旋转 image.RemovePropertyItem(0x0112); return image; }
步骤2:使用修正后的图片
string OriginalFileLocation = "你的图片路径"; using (var fileStream = new FileStream(OriginalFileLocation, FileMode.Open)) using (var sourceImage = System.Drawing.Image.FromStream(fileStream)) using (var fixedImage = FixImageOrientation(sourceImage)) { // 此时fixedImage的Width和Height就是正确的实际尺寸 Console.WriteLine($"修正后宽度: {fixedImage.Width}, 修正后高度: {fixedImage.Height}"); // 可以在这里对fixedImage进行后续处理,比如保存 fixedImage.Save("修正后的图片路径.jpg"); }
内容的提问来源于stack exchange,提问作者luke
相关产品推荐
相关产品推荐

