Saving WPF bitmap effect resultant image

你离开我真会死。 提交于 2021-02-08 07:26:22

问题


I have a image to be displayed in the page and then apply some visual effects to the image. e.g Bevel effect. Once the effect is applied successfully is there a way to save the resultant image?


回答1:


you can do something like this

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;
        }
    }


来源:https://stackoverflow.com/questions/4406290/saving-wpf-bitmap-effect-resultant-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!