设置加载到 canvas wpf c# 上的图像的分辨率

set resolution of image loaded on canvas wpf c#

我正在处理 canvas 并在其上加载图像。如何将图像的分辨率设置为 640X480 像素? decodepixelheight 和 decodepixelwidth 不工作。

   ImageBrush brush = new ImageBrush();
        BitmapImage src = new BitmapImage(new Uri(("C:\Users\i2v\Desktop\GoogleMapTA.jpg"), UriKind.Relative));
        src.DecodePixelHeight = 480;
        src.DecodePixelWidth = 640;
        brush.ImageSource = src;
     //   brush.Stretch = Stretch.None;
        canvas.Background = brush;
        canvas.Height = src.Height;
        canvas.Width = src.Width;

BitmapImage 实现了 System.ComponentModel.ISupportInitialize 接口。这意味着它的属性只能在其 BeginInitEndInit 方法的调用之间设置:

var src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(@"C:\Users\i2v\Desktop\GoogleMapTA.jpg");
src.DecodePixelHeight = 480;
src.DecodePixelWidth = 640;
src.EndInit();

canvas.Background = new ImageBrush(src);

请注意,您通常不会同时设置 DecodePixelWidthDecodePixelHeight,因为这可能会破坏图像的原始纵横比。设置其中一个。