2-rle.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (C) 2018 Tom Li <tomli at tomli.me>.
  3. *
  4. * This software is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU Lesser General Public License as published by
  6. * the Free Software Foundation; either version 3, or (at your option) any
  7. * later version.
  8. *
  9. * This software is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  11. * or FITNESS FOR A PARTICULAR PURPOSE.
  12. *
  13. * See COPYING for terms and conditions.
  14. *
  15. * GPL or LGPL does __not__ require attribution beyond preserving and
  16. * following the license, but if you find my code is useful or inspirational
  17. * to your own project, I'd be thankful if you attribute my name.
  18. */
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #include <unistd.h>
  22. #include <string.h>
  23. int main(int argc, char **argv)
  24. {
  25. FILE *f;
  26. FILE *f2;
  27. long size;
  28. char name[256];
  29. if (argc != 2) {
  30. fprintf(stderr, "error: too many or no argument, should be\n");
  31. fprintf(stderr, "%s [A RGB565 INPUT FILE]\n", argv[0]);
  32. return 1;
  33. }
  34. strncpy(name, argv[1], 64);
  35. name[64] = '\0';
  36. f = fopen(name, "rb");
  37. fseek(f, 0, SEEK_END);
  38. size = ftell(f) / 2;
  39. fseek(f, 0, SEEK_SET);
  40. strcat(name, ".rle");
  41. f2 = fopen(name, "w+");
  42. //printf("size: %lu\n", size);
  43. uint16_t color = 0;
  44. uint16_t color2 = 0;
  45. uint8_t length = 1;
  46. for (long i = 0; i < size; i++) {
  47. fread(&color2, sizeof(color), 1, f);
  48. //printf("%x\n", color2);
  49. if (color == color2) {
  50. length++;
  51. //printf("%d\n", length);
  52. }
  53. //printf("%ld %ld\n", i, size);
  54. if (i != 0 && (color != color2 || length == 255 || i == size - 1)) {
  55. //printf("write -> %d %x\n", length, color);
  56. fwrite(&length, sizeof(length), 1, f2);
  57. fwrite(&color, sizeof(color), 1, f2);
  58. length = 1;
  59. }
  60. color = color2;
  61. }
  62. //printf("write -> %d %x\n", length, color);
  63. fwrite(&length, sizeof(length), 1, f2);
  64. fwrite(&color, sizeof(color), 1, f2);
  65. fclose(f);
  66. fclose(f2);
  67. }