### 14.2.4 Creating or recreating images: writergb

The writergb writes images to png files; the image can either be read in with readrgb or created by writergb itself.

#### Writing images given in Xcas format

To write an existing image, the writergb command takes two arguments, a file name and an image in Xcas format (see section 14.2.1).

writergb writes the image to the given file.

As an example, suppose the following image is stored in file image1234.jpg.

Using readrgb,

a := readrgb("image1234.jpg")

the variable a will contain a list,

- a[0] will be [4,250,500], the number of channels, the height and the width of the image.
- a[1], the red channel,
- a[2], the green channel,
- a[3], the transparency channel,
- a[4], the blue channel.

The command
Input:

writergb("image2134.png",[a[0],a[2],a[1],a[3],a[4]])

will produce an image file image2134.png which is simply image1234.png with the green and red colors switched.

#### Creating images

The Xcas image format can be typed in by hand.
Input:

writergb("image1.png",[[4,2,2],[[255,0],[0,0]],[[0,255],[0,0]], [[255,125],[255,255]],[[0,0],[255,0]]])

creates a file image1.png containing an image 2 points by 2 points, the upper left point is red, the upper right point is a muted green, the lower left point is blue, and the lower right point is black. The transparency value of 125 for the upper right point makes it partially transparent and mutes the color.

For larger images, in some cases the matrix operations of Xcas can be used to create the channels.
Input:

writergb("image2.png",[[4,300,300],makemat(0,300,300), makemat(0,300,300), makemat(255,300,300),makemat(0,300,300) + idn(300)*255])

The writergb command can also take as input a simplified version of the Xcas image description, which doesn’t involve stating the number of channels, the size of the image, or the transparency. There is a full color version of this simplified form and a grayscale version.

To create a full color image, the writergb command takes four arguments, the name of the file to store the image, the red channel (matrix), the green channel and the blue channel.
Input:

writergb("image2.png",[[255,250],[0,120]],[[0,255],[0,0]],[[0,0],[255,100]])

creates a file image2.png containing an image 2 points by 2 points, the upper left point is red (rgb value (255,0,0)), the upper right point is yellow (rgb value (250,255,0)), the lower left point is blue (rgb value (0,0,255) and the lower right point is violet (rgb value (120,0,100)).

To create a grayscale image, the writergb command takes two arguments, the name of the file to store the image and a matrix representing how dark each point is (where 0 is black and 255 is white).
Input:

writergb("image3.png",[[65,125],[185,200]])

creates a file image3.png containing an image 2 points by 2 points, the upper left point is dark gray, the upper right point is medium gray, the lower left point is light gray and the lower right point is even lighter gray.