0

I want to create a console program which, when run, creates an image file with some programmatically generated drawings. It will eventually read some configuration file with numeric parameters, then create the image algorithmically.

I can already get what I want with HTML5 Canvas and Javascript, using drawing commands like fillRect(), etc.

I have taken a look at the (excessively) vast .NET documentation about this, specially System.Drawing and System.Windows.Media namespaces, but there seems to be so many ways to use those classes that I don't even know where to start.

A pseudocode (not actual class names!!!) example of what I plan to do would be this:

RasterImage raster = new RasterImage(width, height);
context = raster.getContext();
context.fillColor = 'white';
context.DrawRectangle(x,y,w,h);
context.saveAsPng('result.png');

I believe an actual solution would be much more verbose than this, but that is the current workflow I need to perform. Also, it would be interesting if this class could not depend too much on WPF (it's a console program), but actually use more generic drawing classes if possible. Thanks in advance!

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • 2
    Possible duplicate: http://stackoverflow.com/questions/2070365/how-to-generate-an-image-from-text-on-fly-at-runtime – Alina B. Mar 02 '13 at 14:08

1 Answers1

3

Using the System.Drawing.Bitmap class and it's entourage, you could do it very simply like:

static void Main(string[] args) {

    int width = 512;
    int height = 512;

    int x, y, w, h;
    x = y = 10;
    w = h = 100;

    using (Bitmap bmp = new Bitmap(width, height)) {
        using (Graphics g = Graphics.FromImage(bmp)) {

            g.FillRectangle(
                brush: new SolidBrush(
                    color: Color.Blue
                ),
                rect: new Rectangle(x, y, w, h)
            );

            g.DrawRectangle(
                pen: new Pen(
                    color: Color.Black, 
                    width: 3
                ),
                rect: new Rectangle(x, y, w, h)
            );

            bmp.Save(@"D:\result.png", ImageFormat.Png);

        }
    }

}

You will need to reference the System.Drawing assembly and also add the following using clauses:

using System.Drawing;
using System.Drawing.Imaging;
Eduard Dumitru
  • 3,242
  • 17
  • 31