Question

So it is needed to be sayd im completely new to WPF and XAML. I got as a project to make a program that when you insert a picture you must add effects some to it.I dont really know much about WPF so I need your help. I need 1 effect from you guys so i can have an example to make the other ones.

Was it helpful?

Solution

Create your image in memory or on a page like so:

<Image Source="sourceimage.png" Name="myImage">
    <Image.Effect>
        <BlurEffect />
    </Image.Effect>
</Image>

Next you'll need the following function to save a visual into a bitmap (there are easier/simpler ways to do this but this function handles certain fringe cases better):

    private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
    {
        if (target == null)
        {
            return null;
        }
        Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
        RenderTargetBitmap 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);
        return rtb;
    }

Finally save it to a file using something like a PNG encoder:

var bitmap = CaptureScreen(this.myImage, 96, 96);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var s = File.Create(@"filename.png"))
    encoder.Save(s);

Keep in mind though that if you're saving an image that has been added to an on-screen window then you'll have to do all this in the Loaded handler or something, if you try and do it before all the framework elements have been initialized then your image will be blank.

Now that I've said all this let me just say I think it's a reall, REALLY bad idea to use WPF for doing things like this. WPF shader effects are notoriously flakey, as are many of the hardware drivers it relies on, and you'd be much better using a proper image processing library.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top