C# Console Application - How to draw in BMP/JPG fi

2019-05-11 18:25发布

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!

2条回答
劳资没心,怎么记你
2楼-- · 2019-05-11 19:06
  • 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");
查看更多
等我变得足够好
3楼-- · 2019-05-11 19:24

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.

查看更多
登录 后发表回答