io.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "io.h"
  2. #include "os.h"
  3. #include "bmp_io.h"
  4. #include "png_io.h"
  5. #include <stdio.h> /* For fputs() */
  6. #include <string.h> /* For strcmp() */
  7. #include <ctype.h> /* For tolower() */
  8. const char *getExtension(const char *fname, size_t len)
  9. {
  10. if (fname == NULL || len <= 0) return NULL;
  11. while (--len > 0 && fname[len] != '.' && fname[len] != '\0')
  12. ;
  13. return fname + len + 1;
  14. }
  15. MMImageType imageTypeFromExtension(const char *extension)
  16. {
  17. char ext[4];
  18. const size_t maxlen = sizeof(ext) / sizeof(ext[0]);
  19. size_t i;
  20. for (i = 0; extension[i] != '\0'; ++i) {
  21. if (i >= maxlen) return kInvalidImageType;
  22. ext[i] = tolower(extension[i]);
  23. }
  24. ext[i] = '\0';
  25. if (strcmp(ext, "png") == 0) {
  26. return kPNGImageType;
  27. } else if (strcmp(ext, "bmp") == 0) {
  28. return kBMPImageType;
  29. } else {
  30. return kInvalidImageType;
  31. }
  32. }
  33. MMBitmapRef newMMBitmapFromFile(const char *path,
  34. MMImageType type,
  35. MMIOError *err)
  36. {
  37. switch (type) {
  38. case kBMPImageType:
  39. return newMMBitmapFromBMP(path, err);
  40. case kPNGImageType:
  41. return newMMBitmapFromPNG(path, err);
  42. default:
  43. if (err != NULL) *err = kMMIOUnsupportedTypeError;
  44. return NULL;
  45. }
  46. }
  47. int saveMMBitmapToFile(MMBitmapRef bitmap,
  48. const char *path,
  49. MMImageType type)
  50. {
  51. switch (type) {
  52. case kBMPImageType:
  53. return saveMMBitmapAsBMP(bitmap, path);
  54. case kPNGImageType:
  55. return saveMMBitmapAsPNG(bitmap, path);
  56. default:
  57. return -1;
  58. }
  59. }
  60. const char *MMIOErrorString(MMImageType type, MMIOError error)
  61. {
  62. switch (type) {
  63. case kBMPImageType:
  64. return MMBMPReadErrorString(error);
  65. case kPNGImageType:
  66. return MMPNGReadErrorString(error);
  67. default:
  68. return "Unsupported image type";
  69. }
  70. }