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

无人久伴 提交于 2019-12-07 12:22:36

问题


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!


回答1:


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.




回答2:


  • 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");


来源:https://stackoverflow.com/questions/15137449/c-sharp-console-application-how-to-draw-in-bmp-jpg-file-using-gdi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!