保存WPF位图效果结果图像

时间:2010-12-10 06:27:37

标签: wpf .net-3.5 bitmap effects

我有一个要在页面中显示的图像,然后对图像应用一些视觉效果。例如斜角效应。一旦成功应用效果,有没有办法保存结果图像?

1 个答案:

答案 0 :(得分:5)

你可以做这样的事情

private void SaveImage()
    {
        try
        {

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "JPeg Image(*.JPG)|*.jpg|Bitmap Image(*.BMP)|*.bmp|Png Image(*.PNG)|*.png|Gif Image(*.GIF)|*.gif";

            if (saveDialog.ShowDialog().Value == true)
            {
                // Save current canvas transform
                Transform transform = img.LayoutTransform;
                // reset current transform (in case it is scaled or rotated)
                img.LayoutTransform = null;

                // Get the size of canvas
                Size size = new Size(img.ActualWidth, img.ActualHeight);
                // Measure and arrange the surface
                // VERY IMPORTANT
                img.Measure(size);
                img.Arrange(new Rect(size));

                // Create a render bitmap and push the surface to it
                RenderTargetBitmap renderBitmap =
                  new RenderTargetBitmap(
                    (int)size.Width,
                    (int)size.Height,
                    96d,
                    96d,
                    PixelFormats.Default);
                renderBitmap.Render(img);
                BitmapEncoder encoder = new BmpBitmapEncoder();
                string extension = saveDialog.FileName.Substring(saveDialog.FileName.LastIndexOf('.'));
                switch (extension.ToLower())
                {
                    case ".jpg":
                        encoder = new JpegBitmapEncoder();
                        break;
                    case ".bmp":
                        encoder = new BmpBitmapEncoder();
                        break;
                    case ".gif":
                        encoder = new GifBitmapEncoder();
                        break;
                    case ".png":
                        encoder = new PngBitmapEncoder();
                        break;
                }
                // push the rendered bitmap to it
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                // Create a file stream for saving image
                using (FileStream fs = File.Open(saveDialog.FileName, FileMode.OpenOrCreate))
                {
                    encoder.Save(fs);
                }
                // Restore previously saved layout
                img.LayoutTransform = transform;
            }

        }
        catch (Exception)
        {

            throw;
        }
    }