使用两种不同的文件格式绑定Image Source时出现问题

时间:2014-07-23 09:29:17

标签: c# wpf image imagesource

我的应用程序需要.tiff和.png图片,当我上传.tiff图片image.Source.Height时,image.Source.Width设置为比上传的.tiff图片的实际尺寸更小的值。但是,当我上传.png图片image.Source.Height时,image.Source.Width设置为实际图片值。为什么会这样?

2 个答案:

答案 0 :(得分:2)

ImageSource宽度和高度与PixelWidth和PixelHeight不同。 DPI改变宽度和高度。

注意:如果要调整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;
    }

答案 1 :(得分:1)

您应该使用:

Image.Source.PixelWidth

以像素为单位确定宽度。

实际上,Width参数取决于图像的dpi值,而pixelwidth则不然。