Interactive Session #5: Creating and editing image files

Image manipulation is provided through the System.Drawing package. To create drawings you need to create a bitmap first.

> open System.Drawing;;
> let bitmap = new Bitmap(10, 10);;

val bitmap : Bitmap

You may edit the bitmap directly by setting individual pixels. Colors need to be specified using the Color type. The function FromArgb takes either 3 arguments: Red, Green, Blue or 4 arguments: Alpha, Red, Green, Blue. Alpha values range from 0 (transparent) to 255 (opaque). Color values also range from 0 to 255.

> let black = Color.FromArgb(0, 0, 0);;

val black : Color = Color [A=255, R=0, G=0, B=0]

> let blue = Color.Blue;;        

val blue : Color = Color [Blue]

> bitmap.SetPixel(0, 0, black);;
val it : unit = ()
> bitmap.SetPixel(1, 0, blue);;
val it : unit = ()
> bitmap.SetPixel(2, 0, blue);;
val it : unit = ()
> bitmap.SetPixel(3, 0, blue);;
val it : unit = ()
> bitmap.Save("simple1.png");;
val it : unit = ()

The resulting image should look as follows. Only 4 pixels have been set, the rest of the bitmap is transparent.

You may rotate this bitmap with the RotateFlip function. RotateFlip takes as an argument a value of type RotateFlipType which may be any of the following:

> RotateFlipType.Rotate90FlipXY
> RotateFlipType.Rotate90FlipY
> RotateFlipType.Rotate90FlipX
> RotateFlipType.Rotate90FlipNone
> RotateFlipType.Rotate180FlipXY
> RotateFlipType.Rotate180FlipY
> RotateFlipType.Rotate180FlipX
> RotateFlipType.Rotate180FlipNone
> RotateFlipType.Rotate270FlipXY
> RotateFlipType.Rotate270FlipY
> RotateFlipType.Rotate270FlipX
> RotateFlipType.Rotate270FlipNone

> bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);;
val it : unit = ()
> bitmap.Save("simple2.png");;

The resulting image should look as follows:

You may create a bitmap also from stored images.

> let image = Image.FromFile("simple1.png");;

val image : Image

> let bitmap = new Bitmap(image);;

val bitmap : Bitmap

Further reading: Working with Images, Bitmaps, Icons, and Metafiles

Advertisements
This entry was posted in GUI, IO. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s