~ajpaon/image-to-ansi

ab8bc47fa2dc281549b0963e8aa049963cc248d3 — Andrew Paon 1 year, 4 months ago 1e196b4 master
account for padding in bmp rows

bmp pads pixel rows to multiples of 4 bytes
1 files changed, 12 insertions(+), 5 deletions(-)

M main.c
M main.c => main.c +12 -5
@@ 126,25 126,32 @@ int main(int argc, char *argv[]) {
  }

  const int bytes_per_pixel = 3;
  const int bits_per_pixel = bytes_per_pixel * 8;

  // equation from https://en.wikipedia.org/wiki/BMP_file_format#Pixel_storage
  int bytes_per_row = (bits_per_pixel * bmp.width + 31) / 32 * 4;
  int padding_per_row = bytes_per_row - (bmp.width * bytes_per_pixel);

  int bytes_per_row = bytes_per_pixel * bmp.width;
  int pixel_buffer_size = bytes_per_row * bmp.height;

  /* BMP pixel rows are stored bottom-up, left-to-right. Start on the top row --
   * the last one in the buffer -- and work backwards. */

  uint8_t *hp = bmp.pixels + pixel_buffer_size - bytes_per_row - bytes_per_pixel;
  uint8_t *hp = bmp.pixels + pixel_buffer_size - bytes_per_row;
  uint8_t *lp = hp - bytes_per_row;

  for (int y = 0; y < bmp.height / 2; ++y) {
    for (int x = 0; x < bmp.width; ++x) {
      hp += bytes_per_pixel;
      lp += bytes_per_pixel;
      printf("\033[48;2;%u;%u;%um", hp[2], hp[1], hp[0]);
      printf("\033[38;2;%u;%u;%um", lp[2], lp[1], lp[0]);
      fputs("\u2584", stdout);

      hp += bytes_per_pixel;
      lp += bytes_per_pixel;
    }

    hp += padding_per_row;
    lp += padding_per_row;

    hp -= 3 * bytes_per_row;
    lp -= 3 * bytes_per_row;