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

I have an image in a System.Drawing.Image object, and I need to create an ImageBrush object (used for the Fill Rectangle property in WPF, for example) from it. I suppose there must be a way to do this, but I cannot find it.

+5
source share
2 answers
      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, does not free the descriptor memory. For information on how to remove a memory leak, see WPF Memory Leak CreateBitmapSourceFromHBitmap ()

+13
source
<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 tied to the viewmodel. You can replace the snap with uri image.

+2
source

All Articles