3

我想使用 C# 控制台应用程序和 GDI+ 在 BMP 或 JPG 文件中绘制矩形、箭头、文本、线条等形状。这是我在网上找到的:

c# 将 System.Drawing.Graphics 保存到文件c# 将 System.Drawing.Graphics 保存到文件 GDI+ 初学者教程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

但这仍然对我没有帮助。其中一些链接仅针对 Windows 窗体应用程序解释这一点,而其他链接仅供参考(MSDN 链接),仅解释 GDI+ 中的类、方法等。那么如何使用 C# 控制台应用程序绘制图片文件呢?谢谢!

4

2 回答 2

8

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.

于 2013-02-28T14:13:58.297 回答
2
  • 添加对程序集的引用:System.Drawing(在 System.Drawing.dll 中)
  • 添加使用:命名空间:System.Drawing
  • 创建一个空的Bitmap,例如var bitmap = new Bitmap(width, height);
  • 为该Bitmap创建Graphics对象:var graphics = Graphics.FromImage(bitmap);
  • 使用图形对象方法在位图上绘制,例如graphics.DrawRectangle(Pens.Black, 0, 0, 10, 10)
  • 将图像另存为文件:bitmap.Save("MyShapes.png");
于 2013-02-28T14:09:22.807 回答