WPF Visualbrush to Imagesource

1.7k views Asked by At

I would like to save a VisualBrush to a file. I've tried many different solutions but nothing worked. I've tried to write a simple Converter:

public class BrushToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is Brush)
        {
            var brush = (Brush)value;
            Size size = new Size(1000, 1000);
            if (parameter is Size)
                size = (Size)parameter;

            RenderTargetBitmap bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
            if (brush is VisualBrush)
            {
                bitmap.Render(((VisualBrush)brush).Visual);
            }
            else
            {
                var drawingVisual = new DrawingVisual();
                using (DrawingContext context = drawingVisual.RenderOpen())
                {
                    context.DrawRectangle(brush, null, new Rect(0, 0, bitmap.Width, bitmap.Height));
                }

                bitmap.Render(drawingVisual);
            }

            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(File.OpenWrite(ViewModel.MainViewModel.Random.Next().ToString() + ".png"));

            return (ImageSource)bitmap;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

All in all the result is a black image. But if I change the source brush to something like Brushes.Red, the result is a red image. So I would guess that the rendering to the bitmap fails, but the saveing to a file works.

Does anyone has an idea what I am doing wrong?

0

There are 0 answers