Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF some images are rotated when loaded

Tags:

c#

wpf

xaml

I am new to WPF and cannot find some workaround. I have a basic image controll defined in XAML. I am loading bitmap images dynamically to this controll. The problem is that some of the bitmaps get flipped in the Image controll, when it's loaded and I want to load all images with it's default orientation.

This is my XAML:

<StackPanel Width="Auto" DockPanel.Dock="Left" Margin="1,1,0,1" Orientation="Vertical" Background="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}" HorizontalAlignment="Left" VerticalAlignment="Stretch" Height="Auto" >
   <Image x:Name="Photo"  Stretch="Uniform"  Height="149" Width="134" Margin="21,25,0,20" HorizontalAlignment="Left" VerticalAlignment="Top" />
</StackPanel>

c# code:

BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(child.profilPoto.path, UriKind.Absolute);
img.EndInit();
Photo.Source = img;

thanks

EDIT:

Here is a link for image: img On the left side there is a how the image is displayed in WPF. On the right side is original image.

EDIT 2: Original image

SOLVED Thanks to all. It was metadata issue. I had a lot of photos with bad metadata. When i tried to load images from other camera it was ok. After saving broken images in some editor the photos loaded properly.

like image 381
user2957509 Avatar asked Sep 16 '25 18:09

user2957509


1 Answers

Be cause BitmapMetadata, This is my code, And it works corectly

private static string _orientationQuery = "System.Photo.Orientation";
public static BitmapSource LoadImageFile(String path)
{
  Rotation rotation = Rotation.Rotate0;
  using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
  {
    BitmapFrame bitmapFrame = BitmapFrame.Create(fileStream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
    BitmapMetadata bitmapMetadata = bitmapFrame.Metadata as BitmapMetadata;

    if ((bitmapMetadata != null) && (bitmapMetadata.ContainsQuery(_orientationQuery)))
    {
      object o = bitmapMetadata.GetQuery(_orientationQuery);

      if (o != null)
      {
        switch ((ushort)o)
        {
          case 6:
            {
              rotation = Rotation.Rotate90;
            }
            break;
          case 3:
            {
              rotation = Rotation.Rotate180;
            }
            break;
          case 8:
            {
              rotation = Rotation.Rotate270;
            }
            break;
        }
      }
    }
  }

  BitmapImage _image = new BitmapImage();
  _image.BeginInit();
  _image.UriSource = new Uri(path);
  _image.Rotation = rotation;
  _image.EndInit();
  _image.Freeze();

  return _image;
}
like image 103
Lâm Quang Minh Avatar answered Sep 19 '25 07:09

Lâm Quang Minh