Images are rotated in PictureBox

后端 未结 2 1183
我在风中等你
我在风中等你 2020-12-02 00:26

As the question implies, when I load an image into a pictureBox (using dialog box), it doesn\'t appear as its original look. in this screen shoot, the image on the left is t

2条回答
  •  隐瞒了意图╮
    2020-12-02 01:12

    When you view an image in Windows Photo Viewer, it automatically corrects image orientation if it has an Exif orientation data. PictureBox doesn't have built-in support for such functionality. You can create a custom PictureBox which shows images correctly even if they have orientation data:

    using System.Linq;
    using System.Windows.Forms;
    using System.Drawing;
    using System.ComponentModel;
    
    public class MyPictureBox : PictureBox
    {
        private void CorrectExifOrientation(Image image)
        {
            if (image == null) return;
            int orientationId = 0x0112;
            if (image.PropertyIdList.Contains(orientationId))
            {
                var orientation = (int)image.GetPropertyItem(orientationId).Value[0];
                var rotateFlip = RotateFlipType.RotateNoneFlipNone;
                switch (orientation)
                {
                    case 1: rotateFlip = RotateFlipType.RotateNoneFlipNone; break;
                    case 2: rotateFlip = RotateFlipType.RotateNoneFlipX; break;
                    case 3: rotateFlip = RotateFlipType.Rotate180FlipNone; break;
                    case 4: rotateFlip = RotateFlipType.Rotate180FlipX; break;
                    case 5: rotateFlip = RotateFlipType.Rotate90FlipX; break;
                    case 6: rotateFlip = RotateFlipType.Rotate90FlipNone; break;
                    case 7: rotateFlip = RotateFlipType.Rotate270FlipX; break;
                    case 8: rotateFlip = RotateFlipType.Rotate270FlipNone; break;
                    default: rotateFlip = RotateFlipType.RotateNoneFlipNone; break;
                }
                if (rotateFlip != RotateFlipType.RotateNoneFlipNone)
                {
                    image.RotateFlip(rotateFlip);
                    image.RemovePropertyItem(orientationId);
                }
            }
        }
        [Localizable(true)]
        [Bindable(true)]
        public new Image Image
        {
            get { return base.Image; }
            set { base.Image = value; CorrectExifOrientation(value); }
        }
    }
    

提交回复
热议问题