Search code examples
c#wpfimageimagesource

Issue in binding Image Source with two different file format


My application takes .tiff and .png images, when I upload .tiff image image.Source.Height and image.Source.Width is set to smaller values than actual dimensions of uploaded .tiff image. But when I upload .png image image.Source.Height and image.Source.Width is set to actual image values. Why is this happening?


Solution

  • ImageSource Width and Height are different from PixelWidth and PixelHeight. DPI change the Width and Height.

    Note : If you want to resize a BitmapSource :

    public static BitmapImage BitmapImageFromBitmapSourceResized(BitmapSource bitmapSource, int newWidth)
        {
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            MemoryStream memoryStream = new MemoryStream();
            BitmapImage bImg = new BitmapImage();
    
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(memoryStream);
    
            bImg.BeginInit();
            bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
            bImg.DecodePixelWidth = newWidth;
            bImg.EndInit();
            memoryStream.Close();
            return bImg;
        }