作者: Andy. 时间: 2016-09-10 08:54:15
先说问题,因为要根据模板生成word。但是总有几张图片不按规矩来,指定悬浮插入(Shape AddPicture(System.String FileName, ref System.Object LinkToFile, ref System.Object SaveWithDocument, ref System.Object Left, ref System.Object Top, ref System.Object Width, ref System.Object Height, ref System.Object Anchor);)的时候总飘到了该页的左上角。下条件断点调试。发现了一个奇葩问题,看图片:
实际上都出来的宽高和文件管理器里面查看的宽高并不一致,估计就是旋转了的。因为旋转的原因导致插入位置的问题。现在就给出了两种解决方案:
1、检测出图片旋转过,插入的时候就不插入这一张图片。
2、检测出图片旋转过,把其再旋转后插入。
两种方法,不管那种都要计策旋转,当时的想法是,文件的旋转信息肯定记录再文件头的某个位置。但是怎么读出来呢?读到buffer中再偏移过去。总感觉太过麻烦了,System.Drawing.Image高度封装了的,里面肯定有文件的信息。但是不知道如何读出来。因为除了一个看不懂的PropertyItems,其他都不像,但是这个PropertyItems的信息又太少。只能寄托网上查找,还好已有前人遇到并已解决。链接:C# 图片旋转和获取原图片旋转角度。检测旋转:
public static int readPictureDegree(string path) { int rotate = 0; using (var image = System.Drawing.Image.FromFile(path)) { foreach (var prop in image.PropertyItems) { if (prop.Id == 0x112) { if (prop.Value[0] == 6) rotate = 90; if (prop.Value[0] == 8) rotate = -90; if (prop.Value[0] == 3) rotate = 180; prop.Value[0] = 1; } } } return rotate; }
说实话,我至今都不能理解那个0x112是什么东西...旋转:
public bool KiRotate(string path, RotateFlipType rotateFlipType) { try { using (Bitmap bitmap = new Bitmap(path)) { bitmap.RotateFlip(rotateFlipType); bitmap.Save(path); } return true; } catch(Exception ex) { return false; } }
旋转回原位后插入问题解决~