C# Console Application - How to draw in BMP/JPG file using GDI+?

user2119805 picture user2119805 · Feb 28, 2013 · Viewed 12.4k times · Source

I want to draw shapes like rectangles, arrows, text, lines in a BMP or JPG file, using a C# Console Application and GDI+. This is what I found on the web:

c# save System.Drawing.Graphics to file c# save System.Drawing.Graphics to file GDI+ Tutorial for Beginners http://www.c-sharpcorner.com/UploadFile/mahesh/gdi_plus12092005070041AM/gdi_plus.aspx Professional C# - Graphics with GDI+ codeproject.com/Articles/1355/Professional-C-Graphics-with-GDI

But this still doesn't help me. Some of these links explains this only for a Windows Forms Application and other links are only for reference (MSDN links), explaining only classes, methods etc. in GDI+. So how can I draw in a picture file using a C# Console Application? Thank you!

Answer

Hans Passant picture Hans Passant · Feb 28, 2013

It is pretty straight-forward to create bitmaps in a console mode app. Just one minor stumbling block, the project template doesn't preselect the .NET assembly you need. Project + Add Reference, select System.Drawing

A very simple example program:

using System;
using System.Drawing;   // NOTE: add reference!!

class Program {
    static void Main(string[] args) {
        using (var bmp = new Bitmap(100, 100))
        using (var gr = Graphics.FromImage(bmp)) {
            gr.FillRectangle(Brushes.Orange, new Rectangle(0, 0, bmp.Width, bmp.Height));
            var path = System.IO.Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                "Example.png");
            bmp.Save(path);
        }
    }
}

After you run this you'll have a new bitmap on your desktop. It is orange. Get creative with the Graphics methods to make it look the way you want.