VB.Net中RichTextBox粘贴JPG图片自动旋转90度的问题解决
解决RichTextBox粘贴JPG自动旋转问题
我用VB.Net编写程序,将JPG图片粘贴到RichTextBox控件中,核心代码如下:
For Each Picture As String In ShopAndCraftItem.FileList Dim img As Image = System.Drawing.Image.FromFile(Directory_Server.ShopAndCraftsPictureFilePath & "\" & Picture) Clipboard.SetImage(img) Me.rtfReport.AppendText(m_Tab_2) Me.rtfReport.Paste() Me.rtfReport.AppendText(vbCrLf) Me.rtfReport.Font = SC_BoldFont Me.rtfReport.AppendText(m_Tab_1 & "Picture".PadRight(ReportPad, ".") & Picture & vbCrLf) Next
其中ShopAndCraftItem.FileList是自定义类,存储店铺/手工物品分类关联的图片文件名列表;Directory_Server是自定义目录操作类,rtfReport是标准RichTextBox控件。
程序运行基本正常,但部分小型数码相机拍摄的JPG粘贴后会自动旋转90度——磁盘中图片显示正常,仅粘贴到RichTextBox时出现问题。需要从根源解决,或通过编程自动识别并纠正旋转。
问题原因
数码相机拍摄的JPG会携带EXIF方向标签,记录拍摄时的设备朝向。但System.Drawing.Image.FromFile方法不会自动应用这个旋转信息,RichTextBox粘贴时也不处理该标签,导致图片按原始像素方向显示,和系统看图软件的显示效果不一致。
解决方案
读取图片的EXIF方向属性,根据标签值对图片进行旋转/翻转处理后,再粘贴到RichTextBox。
修改后的代码
首先添加辅助函数处理旋转逻辑,再调整核心代码:
' 根据EXIF方向标签获取对应的旋转翻转类型 Private Function GetRotateFlipTypeFromExif(img As Image) As RotateFlipType Const ExifOrientationTagId As Integer = 274 ' EXIF方向标签的固定ID If img.PropertyIdList.Contains(ExifOrientationTagId) Then Dim orientationValue As Integer = CType(img.GetPropertyItem(ExifOrientationTagId).Value(0), Integer) Select Case orientationValue Case 1 : Return RotateFlipType.RotateNoneFlipNone ' 正常方向 Case 2 : Return RotateFlipType.RotateNoneFlipX ' 水平翻转 Case 3 : Return RotateFlipType.Rotate180FlipNone ' 旋转180度 Case 4 : Return RotateFlipType.Rotate180FlipX ' 旋转180度+水平翻转 Case 5 : Return RotateFlipType.Rotate90FlipX ' 顺时针转90度+水平翻转 Case 6 : Return RotateFlipType.Rotate90FlipNone ' 顺时针转90度 Case 7 : Return RotateFlipType.Rotate270FlipX ' 顺时针转270度+水平翻转 Case 8 : Return RotateFlipType.Rotate270FlipNone ' 顺时针转270度 Case Else : Return RotateFlipType.RotateNoneFlipNone End Select End If Return RotateFlipType.RotateNoneFlipNone End Function ' 处理图片并粘贴的核心代码 For Each Picture As String In ShopAndCraftItem.FileList Dim imgPath As String = Path.Combine(Directory_Server.ShopAndCraftsPictureFilePath, Picture) ' 使用Using确保图片资源自动释放 Using originalImg As Image = Image.FromFile(imgPath) Dim rotateType As RotateFlipType = GetRotateFlipTypeFromExif(originalImg) ' 复制图片并应用旋转翻转 Using processedImg As Image = CType(originalImg.Clone(), Image) processedImg.RotateFlip(rotateType) Clipboard.SetImage(processedImg) Me.rtfReport.AppendText(m_Tab_2) Me.rtfReport.Paste() Me.rtfReport.AppendText(vbCrLf) Me.rtfReport.Font = SC_BoldFont Me.rtfReport.AppendText(m_Tab_1 & "Picture".PadRight(ReportPad, ".") & Picture & vbCrLf) End Using End Using Next
注意事项
- 用
Using语句包裹图片对象,避免内存泄漏; - 使用
Path.Combine拼接路径,比字符串拼接更安全,避免分隔符错误; - 若不需要处理翻转场景,可简化
GetRotateFlipTypeFromExif函数,只保留旋转相关的分支。
内容的提问来源于stack exchange,提问作者E Bell
相关产品推荐
相关产品推荐

