How to crop image and save into ImageSource in WPF?

后端 未结 2 1803
滥情空心
滥情空心 2021-02-08 23:56

I am new learner to WPF. here I got a question. I have a image, width:360, height:360. Here I want to crop this image like below:

( 0,0 ) to (120,120) save to the fi

2条回答
  •  一生所求
    2021-02-09 00:42

    Just do:

    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;
    }
    
    VisualBrush part1 = new VisualBrush(yourVISUAL);
    part1.ViewBoxUnits = ..Absolute;
    part1.ViewBox = new Rect(x, y, width, height);
    BitmapSource bitmapSource = CaptureScreen(part1, 96, 96);
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            BitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(fileStream);
        }
    

提交回复
热议问题