Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 823
user2119805 Avatar asked Oct 17 '25 14:10

user2119805


2 Answers

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.

like image 115
Hans Passant Avatar answered Oct 20 '25 04:10

Hans Passant


  • Add reference to the Assembly: System.Drawing (in System.Drawing.dll).
  • Add using: Namespace: System.Drawing.
  • Create an empty Bitmap, e.g. var bitmap = new Bitmap(width, height);
  • Create Graphics object for that Bitmap: var graphics = Graphics.FromImage(bitmap);
  • Use graphics object methods to draw on your bitmap, e.g. graphics.DrawRectangle(Pens.Black, 0, 0, 10, 10);
  • Save your image as a file: bitmap.Save("MyShapes.png");
like image 21
Ryszard Dżegan Avatar answered Oct 20 '25 05:10

Ryszard Dżegan