How to create ImageBrush from System.Drawing.Image in WPF?

13,039

Solution 1

      var image = System.Drawing.Image.FromFile("..."); // or wherever it comes from
      var bitmap = new System.Drawing.Bitmap(image);
      var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
                                                                            IntPtr.Zero,
                                                                            Int32Rect.Empty,
                                                                            BitmapSizeOptions.FromEmptyOptions()
            );
      bitmap.Dispose();
      var brush = new ImageBrush(bitmapSource);          

This solution, however, doesnt free the memory of the handle. For information on how to remove the memory leak see WPF CreateBitmapSourceFromHBitmap() memory leak

Solution 2

<Rectangle  x:Name="RectangleName"                       
                StrokeThickness="1" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Stretch" 
                Width="200"
                Height="300"
                Stroke="Black" >
        <Rectangle.Fill>

                <ImageBrush ImageSource="{Binding SelectedComponentsImage}"  x:Name="ComponentVisualBrush" ViewboxUnits="Absolute" 
                Viewbox="0,0,300,300" ViewportUnits="RelativeToBoundingBox" Stretch="UniformToFill" Viewport="0,0,1,1" 
                RenderOptions.EdgeMode="Aliased"  />

        </Rectangle.Fill>
</Rectangle>

This is with viewmodel Binding. You can replace the Binding with an image uri.

Share:
13,039
bkovacic
Author by

bkovacic

Microsoft MVP for Windows Azure and founder of Axilis, company specialized in developing software solutions based on Microsoft platforms. Over the last six years he was developing desktop, web and mobile applications, but lately he is mostly focused on the development of Windows Azure applications. Programming is his passion ever since elementary school when he stared participating in various IT competitions.

Updated on June 16, 2022

Comments

  • bkovacic
    bkovacic almost 2 years

    I have image in System.Drawing.Image object and I need to create an ImageBrush object (used for Fill property of Rectangle in WPF for example) from it. I guess there should be a way to do this, but I can't find one.