Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 than my entire canvas.

I tried setting the rect.Offset and rect.Location properties but the image is always saved from the upper left corner of my canvas.

Does anyone know how can I achieve my wanted functionality in a similar way?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
630 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...