Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw directly on bitmap (BitmapSource, WriteableBitmap) in WPF?

Tags:

c#

wpf

In GDI+ Winforms I would do:

Bitmap b = new Bitmap(32,32);
Graphics g = Graphics.FromImage(b); 
//some graphics code...`

How to do the same thing in WPF, with a DrawingContext?

like image 464
Mariusz Avatar asked Aug 30 '11 21:08

Mariusz


2 Answers

I see this question was asked in 2011, but I firmly believe that late is better than never, and the only other "answer" nowhere meets this websites criteria for a proper answer, so I will be providing my own to help anyone else that finds this question in the future.

Here is a simple example that shows how to draw a rectangle and saves it to disk. There may be a better (more concise way) of doing this, but alas, every link I've found online results in the same "shrug I don't know" answer.

        public static void CreateWpfImage()
        {
            int imageWidth = 100;
            int imageHeight = 100;
            string outputFile = "C:/Users/Krythic/Desktop/Test.png";
            // Create the Rectangle
            DrawingVisual visual = new DrawingVisual();
            DrawingContext context = visual.RenderOpen();
            context.DrawRectangle(Brushes.Red, null, new Rect(20,20,32,32));
            context.Close();

            // Create the Bitmap and render the rectangle onto it.
            RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(visual);

            // Save the image to a location on the disk.
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            encoder.Save(new FileStream(outputFile, FileMode.Create));
        }

As far as I can tell, RenderTargetBitmap is considered an ImageSource, so you should be able to link that to the image source of wpf controls directly without any sort of conversions.

like image 193
Krythic Avatar answered Nov 04 '22 00:11

Krythic


You can use RenderTargetBitmap to render any WPF content into a Bitmap, since it is, itself, a BitmapSource. With this, you can use standard drawing operations in WPF to "draw" on a bitmap.

like image 20
Reed Copsey Avatar answered Nov 03 '22 22:11

Reed Copsey