Search code examples
textbitmapdrawingallegroallegro5

text file to bitmap in allegro


hello what I'm currently dealing with is the ability to get input from a text file and then convert it into a bitmap and save it to a file.

the input looks like this:

########
#      #
########

and I want to draw it using allegro and instead of # there would be pixels of specified size. Each # should represent a tile (10x10 pixel). So the final result would look like this

link to an image

I've actually drawn it using this code:

 for (int i = 0; i < 80; i++){
        for (int j = 0; j < 10; j++){
            al_draw_pixel(i, j, al_map_rgb(0, 0, 0));
        }
    }
    for (int i = 0; i < 10; i++){
        for (int j = 10; j < 20; j++){
            al_draw_pixel(i, j, al_map_rgb(0, 0, 0));
        }
    }
    for (int i = 70; i < 80; i++){
        for (int j = 10; j < 20; j++){
            al_draw_pixel(i, j, al_map_rgb(0, 0, 0));
        }
    }
    for (int i = 0; i < 80; i++){
        for (int j = 20; j < 30; j++){
            al_draw_pixel(i, j, al_map_rgb(0, 0, 0));
        }
    }

yeah that's pretty bad, so how do I achieve something like that but with a common procedure which would be independent on the text file? thanks for any advice.

note: the only allowed headers are allegro5/allegro.h and allegro5/allegro_image.h


Solution

  • To draw to an image with Allegro 5, you need to do something like:

    ALLEGRO_BITMAP *bmp = al_create_bitmap(640, 480);
    al_set_target_bitmap(bmp);
    

    Now all of your drawing operations will happen on the image. To later save it:

    al_save_bitmap("somefile.bmp", bmp);
    

    You can also use png and jpg as extensions if your image library has support for it enabled.

    Use these functions to read the text file:

    • al_fopen
    • al_fgetc
    • al_feof
    • al_fclose

    Set int x and y to zero. You'll be looping over until the end of the file. On every iteration increment x by one. If you reach a new line character (\n) increment y by one and set x to zero. (You should ignore \r characters.)

    Now, depending on the character read, draw a tile:

    ALLEGRO_BITAMP *tile_to_draw = NULL;
    if (c == '#')
       tile_to_draw = bmp1;
    else if (c == ' ')
       tile_to_draw = bmp2;
    
    if (tile_to_draw)
       al_draw_bitmap(tile_to_draw, x * 10, y * 10, 0);
    

    Of course there's better ways to map characters to tiles than a series of ifs, but the above works and should be enough to help you finish your homework.