tags:

views:

251

answers:

1

Hello, I'm trying to save a wpf control to file, but I'm applying a PixelShader effect to it, and when I try to save, the saved image is entirely white, black or red... deppends on the parameters of the effect.

I'm using the code here: http://stackoverflow.com/questions/59958/wpf-programmatic-binding-on-a-bitmapeffect

how can I properly save it?

thanks!

UPDATE: the code I'm using is:

        BitmapSource bitmap = preview.Source as BitmapImage;
        Rectangle r = new Rectangle();
        r.Fill = new ImageBrush(bitmap);
        r.Effect = effect;
        Size sz = new Size(bitmap.PixelWidth, bitmap.PixelHeight);
        r.Measure(sz);
        r.Arrange(new Rect(sz));
        var rtb = new RenderTargetBitmap(bitmap.PixelWidth, bitmap.PixelHeight, bitmap.DpiX, bitmap.DpiY, PixelFormats.Pbgra32);
        rtb.Render(r);

        PngBitmapEncoder png = new PngBitmapEncoder();
        png.Frames.Add(BitmapFrame.Create(rtb));

        Stream stm = File.Create("new.png");
        png.Save(stm);
        stm.Close();
A: 

Try this piece of code:

    /// <summary>
    /// Creates a screenshot of the given visual at the desired dots/inch (DPI).
    /// </summary>
    /// <param name="target">Visual component of which to capture as a screenshot.</param>
    /// <param name="dpiX">Resolution, in dots per inch, in the X axis. Typical value is 96.0</param>
    /// <param name="dpiY">Resolution, in dots per inch, in the Y axis. Typical value is 96.0</param>
    /// <returns>A BitmapSource of the given Visual at the requested DPI, or null if there was an error.</returns>       
    public static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
    {
        if (target == null)
        {
            return null;
        }

        RenderTargetBitmap rtb = null;

        try
        {
            // Get the actual size
            Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
            rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
                                          (int)(bounds.Height * dpiY / 96.0),
                                          dpiX,
                                          dpiY,
                                          PixelFormats.Pbgra32);

            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext ctx = dv.RenderOpen())
            {
                VisualBrush vb = new VisualBrush(target);
                ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
            }

            rtb.Render(dv);
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine("Error capturing image: " + ex.Message);
            return null;
        }

        return rtb;
    }
Erich Mirabal
didn't work... the image is entire red...