MS Word VBA:InlineShapes.AddPicture导入图片宽高与显示方向不符
问题原因
Word导入图片时会读取图片的EXIF方向元数据,自动旋转图片以匹配拍摄时的朝向,但InlineShape.Width和Height属性返回的是图片文件的原始像素尺寸,不会自动根据旋转后的显示状态调整数值。这就导致你看到图片是纵向显示,但代码读到的是原始横向宽高,反过来也是一样。
获取显示实际宽高的解决方法
直接利用Word已经计算好的Rotation属性,结合原始宽高换算出实际显示的尺寸:
- 先获取图片的原始宽高:
Dim origWidth As Single, origHeight As Single origWidth = myInlineShape.Width origHeight = myInlineShape.Height - 根据旋转角度调整宽高:
Dim actualWidth As Single, actualHeight As Single Select Case myInlineShape.Rotation Case 90, 270 ' 旋转90/270度,宽高互换 actualWidth = origHeight actualHeight = origWidth Case 0, 180 ' 无旋转或180度翻转,宽高不变 actualWidth = origWidth actualHeight = origHeight Case Else ' 处理其他少见的旋转角度 Dim rad As Double rad = myInlineShape.Rotation * 3.1415926 / 180 ' 计算旋转后的投影宽高 actualWidth = Abs(origWidth * Cos(rad)) + Abs(origHeight * Sin(rad)) actualHeight = Abs(origWidth * Sin(rad)) + Abs(origHeight * Cos(rad)) End Select - 用
actualWidth和actualHeight来判断页面方向,就能和图片显示的朝向匹配了。
如果不想依赖Word的旋转属性,也可以提前读取图片的EXIF方向标签(比如用WIA组件),但直接用Rotation属性是最简便的,因为Word已经帮你处理了显示逻辑。
内容的提问来源于stack exchange,提问作者Zns
相关产品推荐
相关产品推荐

