Search code examples
c#wpfimagecanvasdrawing

set resolution of image loaded on canvas wpf c#


I am working on canvas and loading an image on it. How do I set resolution of my image to 640X480 pixels? decodepixelheight and decodepixelwidth not working.

   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;

Solution

  • BitmapImage implements the System.ComponentModel.ISupportInitialize interface. This means that its properties can only be set between calls of its BeginInit and EndInit methods:

    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);
    

    Note that you would usually not set DecodePixelWidth and DecodePixelHeight at the same time, since this might disrupt the native aspect ratio of the image. Set either one or the other.