RingDotNetfor Ring

Images

Create a picture in memory, draw on it, read and change pixels, convert it to gray, resize it and save it as a PNG — all without opening a window.

What you will learn#

Concepts#

An image is a grid of pixels; each pixel has a color made of red, green, blue (0–255) and an alpha value for transparency. A Bitmap is such a grid in memory. To draw on it you use a Graphics object created from the bitmap. A Brush fills areas, a Pen draws lines, a Font draws text.

Note

System.Drawing is part of the desktop runtime, so the using block with System.Drawing starts the desktop runtime even though the program shows no window.

The program#

samples/UsingDotNet/tutorials/ch10_images.ring
# images - create, draw, read pixels, resize, convert to gray and save (no window needed)
#   ring ch10_images.ring [output folder]
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Drawing"
	"System.Drawing.Imaging"
}

func main

	cFolder = new Path().GetTempPath()
	if len(sysargv) >= 3 and left(sysargv[3],2) != "--"           # an option such as --selftest is not a folder
		cFolder = sysargv[3]
		new Directory().CreateDirectory(cFolder)
	ok

	# STEP 1. A bitmap is a rectangle of pixels. Graphics draws on it.
	oBitmap = new Bitmap(240,160)
	oGraphics = new Graphics().FromImage(oBitmap)
	oGraphics.Clear(new Color().White)

	# STEP 2. Draw: brushes fill, pens draw lines
	oBlue = new SolidBrush(new Color().SteelBlue)
	oOrange = new SolidBrush(new Color().Orange)
	oGraphics.FillRectangle([ :brush = oBlue, :rect = new Rectangle(10,10,100,60) ])
	oGraphics.FillEllipse([ :brush = oOrange, :rect = new Rectangle(130,20,90,90) ])
	oPen = new Pen(new Color().Black) {
		Width = 3
	}
	oGraphics.DrawLine([ :pen = oPen, :pt1 = new Point(10,130), :pt2 = new Point(230,90) ])
	oFont = new Font("Segoe UI",14)
	oGraphics.DrawString([ :s = "Hello, image", :font = oFont, :brush = new SolidBrush(new Color().Black), :point = new PointF(12,112) ])
	oGraphics.Dispose()
	? "STEP 2: drew a rectangle, a circle, a line and a text on a " + oBitmap.Width + " x " + oBitmap.Height + " bitmap"

	# STEP 3. Read pixels: GetPixel gives a color
	oPixel = oBitmap.GetPixel(50,40)
	? "STEP 3: pixel (50,40) is R=" + oPixel.R + " G=" + oPixel.G + " B=" + oPixel.B + " (steel blue)"
	? "        pixel (5,5) is  " + oBitmap.GetPixel(5,5).Name + " (white, with alpha ff in front)"

	# STEP 4. Save: the file type is chosen by the format
	cPng = new Path().Combine([cFolder,"ringdotnet_images.png"])
	oBitmap.Save([ :filename = cPng, :format = new ImageFormat().Png ])
	? "STEP 4: saved " + new Path().GetFileName(cPng) + ", " + (new FileInfo(cPng).Length > 0) + " (the file has data)"

	# STEP 5. Load it again and make a gray copy: gray = the average of red, green and blue
	oLoaded = (new Bitmap).@New([ :filename = cPng ])  # a constructor chosen by the name of its parameter
	oGray = new Bitmap(oLoaded.Width,oLoaded.Height)
	for nY = 0 to oLoaded.Height - 1
		for nX = 0 to oLoaded.Width - 1
			oColor = oLoaded.GetPixel(nX,nY)
			nGray = floor((oColor.R + oColor.G + oColor.B) / 3)
			oGray.SetPixel(nX,nY,new Color().FromArgb([ :red = nGray, :green = nGray, :blue = nGray ]))
		next
	next
	cGray = new Path().Combine([cFolder,"ringdotnet_images-gray.png"])
	oGray.Save([ :filename = cGray, :format = new ImageFormat().Png ])
	? "STEP 5: gray copy made, pixel (50,40) is now " + oGray.GetPixel(50,40).R + " in all three channels"

	# STEP 6. Resize: draw the image smaller on a new bitmap
	oSmall = new Bitmap(120,80)
	oSmallGraphics = new Graphics().FromImage(oSmall)
	oSmallGraphics.DrawImage([ :image = oLoaded, :rect = new Rectangle(0,0,120,80) ])
	oSmallGraphics.Dispose()
	cSmall = new Path().Combine([cFolder,"ringdotnet_images-small.png"])
	oSmall.Save([ :filename = cSmall, :format = new ImageFormat().Png ])
	? "STEP 6: resized copy is " + oSmall.Width + " x " + oSmall.Height

	# release the files, remove the temporary ones
	oBitmap.Dispose()
	oLoaded.Dispose()
	oGray.Dispose()
	oSmall.Dispose()
	if not (len(sysargv) >= 3 and left(sysargv[3],2) != "--")      # no output folder was given: remove the files
		new File().Delete(cPng)
		new File().Delete(cGray)
		new File().Delete(cSmall)
	ok
Output
STEP 2: drew a rectangle, a circle, a line and a text on a 240 x 160 bitmap
STEP 3: pixel (50,40) is R=70 G=130 B=180 (steel blue)
        pixel (5,5) is  ffffffff (white, with alpha ff in front)
STEP 4: saved ringdotnet_images.png, 1 (the file has data)
STEP 5: gray copy made, pixel (50,40) is now 126 in all three channels
STEP 6: resized copy is 120 x 80

The three pictures that the program saves:

The drawing
STEP 2: a rectangle, a circle, a line and a text (240 × 160)
The gray copy
STEP 5: the gray copy
The small copy
STEP 6: the resized copy (120 × 80)
Note

This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Drawing#

new Bitmap(240,160) is an empty picture; new Graphics().FromImage(oBitmap) gives the drawing tool; Clear(color) fills the background. Then:

CallDraws
FillRectangle(brush, new Rectangle(x,y,w,h))a filled rectangle
FillEllipse(brush, new Rectangle(x,y,w,h))a filled ellipse (a circle if w = h)
DrawLine(pen, new Point(x1,y1), new Point(x2,y2))a line
DrawString(text, font, brush, new PointF(x,y))text

Colors are new Color().SteelBlue, new Color().Black... (the names of the .NET Color properties). A pen's width is a property: new Pen(color) { Width = 3 }.

Tip

These drawing methods take their arguments in order: a Rectangle or a Point object carries the numbers. In the tutorial Drawing and animation UiCanvas gives shorter calls for simple drawing on screen.

Pixels#

GetPixel(x,y) returns a Color with R, G, B and Name (the hexadecimal text ffffffff: alpha, red, green, blue). Coordinates start at 0. Steel blue is R=70 G=130 B=180, exactly what step 3 prints.

Saving and loading#

oBitmap.Save([ :filename = cPng, :format = new ImageFormat().Png ]) writes the file; the format decides the type (Png, Jpeg, Bmp, Gif). To open a file, dnNew("Bitmap",[ :filename = cPng ]) chooses the constructor by the parameter name.

A gray copy#

A pixel is gray when its red, green and blue are equal. The average (R + G + B) / 3 is a simple conversion. Two loops visit every pixel: for every nY, for every nX, read the color, compute the gray value, write it with SetPixel. new Color().FromArgb([ :red = r, :green = g, :blue = b ]) makes a color from three numbers. Pixel loops are slow in any language that goes through a bridge: for big images use LockBits or leave the work to a library.

Resizing#

Draw the loaded image into a smaller rectangle of a new bitmap: DrawImage(oLoaded, new Rectangle(0,0,120,80)).

Release#

Dispose() frees the picture memory and unlocks the file. Always dispose bitmaps and graphics objects when you are done, and before you delete their file.

What you learned#

Exercises#

  1. Draw a 100 × 100 chessboard with FillRectangle.
  2. Turn the picture into a negative (255 − each channel).
  3. Make a thumbnail that keeps the proportions of any picture: width 100, height 100 × h / w.
  4. Save the same bitmap as a JPEG and compare the file sizes.
  5. Show the picture in a window with a PictureBox (oPicture.Image = oBitmap).

Next#

Screens and pictures of windows

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.