Generating Image Patterns

Computer and art mix very nicely. We can algorithmically generate patterns, be it pictures or music, which are aesthetic.

Here is an example program for *nix systems which generates fractal like tiling. We use tga format, which is simple but uncompressed. For compression, we may use imagemagick suit's convert command.

#include <stdio.h>
#include <fcntl.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>

#define width 1366
#define height 768

char pic[height][width][3];

int main(){
  unsigned int i,j;
  int fd;
  char buffer[100];

  for (i=0; i<height; i++)
    for (j=0; j<width; j++){
    pic[i][j][0] = 0;
    pic[i][j][1] = 0;
    pic[i][j][2] = (((i^(~j))&((~i-350)>>3)))&255;
    }

  if ((fd = open("image.tga", O_RDWR+O_CREAT, S_IRUSR | S_IWUSR)) == -1)
  {
    printf("error opening file\n");
    exit(1);
  }
  buffer[0] = 0;
  buffer[1] = 0;
  buffer[2] = 2;
  buffer[8] = 0;
  buffer[9] = 0;
  buffer[10] = 0;
  buffer[11] = 0;
  buffer[12] = (width & 0x00FF);
  buffer[13] = (width & 0xFF00) >> 8;
  buffer[14] = (height & 0x00FF);
  buffer[15] = (height & 0xFF00) >> 8;
  buffer[16] = 24;
  buffer[17] = 0;
  write(fd, buffer, 18);
  write(fd, pic, width*height*3);
  close(fd);
  return 0;
}

The same program can be written in python too, easier to write, but slower in execution

WIDTH = 1366
HEIGHT = 768

header = [0]*18
header[0] = 0
header[1] = 0
header[2] = 2
header[8] = 0
header[9] = 0
header[10] = 0
header[11] = 0
header[12] = (WIDTH & 0x00FF)
header[13] = (WIDTH & 0xFF00) >> 8
header[14] = (HEIGHT & 0x00FF)
header[15] = (HEIGHT & 0xFF00) >> 8
header[16] = 24
header[17] = 0

if __name__ == "__main__":
    ba = bytearray()

    for i in xrange(HEIGHT):
        for j in xrange(WIDTH):
            blue = 0
            green = 0
            red = (((i ^ (~j)) & ((~i - 350) >> 3))) & 255
            ba.extend(bytearray([blue, green, red]))

    with open("imagepy.tga", "w") as fd:
        fd.write(bytearray(header))
        fd.write(ba)
../../images/pattern.png

Image generated by the program