Saving a WPF canvas as an image

前端 未结 4 537
天命终不由人
天命终不由人 2020-12-16 00:34

I was following this article and I got my canvas to be saved, however, I want to extend the code\'s functionality and save a particular part of my canvas as an image, rather

4条回答
  •  时光取名叫无心
    2020-12-16 01:14

    A simple method would be to use a CroppedBitmap after rendering the whole canvas. You could reuse the same RenderTargetBitmap, if you need multiple images.

    RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas.RenderSize.Width,
        (int)canvas.RenderSize.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);
    rtb.Render(canvas);
    
    var crop = new CroppedBitmap(rtb, new Int32Rect(50, 50, 250, 250));
    
    BitmapEncoder pngEncoder = new PngBitmapEncoder();
    pngEncoder.Frames.Add(BitmapFrame.Create(crop));
    
    using (var fs = System.IO.File.OpenWrite("logo.png"))
    {
        pngEncoder.Save(fs);
    }
    

    If you want to save to a bitmap object instead of a file, you can use:

    using (Stream s = new MemoryStream())
    {
        pngEncoder.Save(s);
        Bitmap myBitmap = new Bitmap(s);
    }
    

提交回复
热议问题