Correct image rotation

I have a simple problem: when I load an image into a window shape PictureBox, some images rotate while others do not.

Basically, the user selects the image from OpenFileDialogand when the image is selected:

private void OpenFD_FileOk(object sender, CancelEventArgs e)
{
    Image image = Image.FromFile(openFD.FileName);
    PB_profile.Image = image;
}

And yes, I checked the original image rotation

EDIT:
I changed the property PictureBox SizeModetoStretchImage

+4
source share
2 answers

If the images contain exif data PropertyItems should include an orientation tag .

It encodes the rotation / flip necessary for the image to display correctly:

PropertyTagOrientation

.

0x0112

1 - 0- , 0- - .
2 - 0- , 0- - .
3 - 0- , 0- - .
4 - 0- , 0- - .
5 - 0- - , 0- - .
6 - 0- - , 0- - .
7 - 0- - , 0- - .
8 - 0- - , 0- - .

PropertyItem:

PropertyItem getPropertyItemByID(Image img, int Id)
{
    return img.PropertyItems.Select(x => x).FirstOrDefault(x => x.Id == Id);
}

GDI + RotateFlip :

void Rotate(Bitmap bmp)
{
    PropertyItem pi = bmp.PropertyItems.Select(x => x)
                                       .FirstOrDefault(x => x.Id == 0x0112);
    if (pi == null) return; 

    byte o = pi.Value[0];

    if (o==2) bmp.RotateFlip(RotateFlipType.RotateNoneFlipX);
    if (o==3) bmp.RotateFlip(RotateFlipType.RotateNoneFlipXY);
    if (o==4) bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
    if (o==5) bmp.RotateFlip(RotateFlipType.Rotate90FlipX);
    if (o==6) bmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
    if (o==7) bmp.RotateFlip(RotateFlipType.Rotate90FlipY);
    if (o==8) bmp.RotateFlip(RotateFlipType.Rotate90FlipXY);
}

.

.

. , . , , , , .

2. , . : , , , !

, exif-, PropertyTagOrientation , 1..

Update: PropertyTagOrientation, :

    using System.Runtime.Serialization;
    ..

    pi = (PropertyItem)FormatterServices
        .GetUninitializedObject(typeof(PropertyItem));

    pi.Id = 0x0112;   // orientation
    pi.Len = 2;
    pi.Type = 3;
    pi.Value = new byte[2] { 1, 0 };

    pi.Value[0] = yourOrientationByte;

    yourImage.SetPropertyItem(pi);

Kudos to @ne1410s !.

, PropertyItems exif-; !

+5

, , EXIF. EXIF ​​ "", . . , , , , , , EXIF. . , #, EXIF, .

+2

Source: https://habr.com/ru/post/1672987/


All Articles