[wpf] how can l output a bitmap form System.Windows.Controls.Image

Whiskey X 1 Reputation point
2020-11-10T09:55:07.73+00:00

This is my Code:

            <Grid>
                <Image x:Name="img" Source="xxx.png" Stretch="Fill">
                    **<Image.Clip>
                        <PathGeometry>
                            <PathFigure StartPoint="0,0">
                                <LineSegment Point="150,50"></LineSegment>
                                <LineSegment Point="150,200"></LineSegment>
                                <BezierSegment Point1="150,200" Point2="100,100" Point3="0,0"></BezierSegment>
                            </PathFigure>
                        </PathGeometry>
                    </Image.Clip>**
                </Image>
            </Grid>

l input a Image and did some Clip with PathGeometry,now l want save the new Image as bitmap?
How Can I do that??

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,755 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. DaisyTian-1203 11,621 Reputation points
    2020-11-11T05:33:34.96+00:00

    You can use the below code to save a image to a bitmap:

     private void SaveToBit()  
            {  
                RenderTargetBitmap rtb = new RenderTargetBitmap(400,400, 96d, 96d, System.Windows.Media.PixelFormats.Default);  
                rtb.Render(img);  
                var crop = new CroppedBitmap(rtb, new Int32Rect(50, 50, 250, 250));  
                BitmapEncoder pngEncoder = new PngBitmapEncoder();  
                pngEncoder.Frames.Add(BitmapFrame.Create(crop));  
                using (Stream s = new MemoryStream())  
                {  
                    pngEncoder.Save(s);  
                    Bitmap myBitmap = new Bitmap(s);  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.