Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.16 KB | None | 0 0
  1. #define STB_IMAGE_IMPLEMENTATION
  2. #include "stb_image.h"
  3. #define STB_IMAGE_WRITE_IMPLEMENTATION
  4. #include "stb_image_write.h"
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8.  
  9. static const char * filepath_to_filename(const char * path)
  10. {
  11.     size_t i, len, lastslash;
  12.  
  13.     len = strlen(path);
  14.     lastslash = 0;
  15.     for(i = 0; i < len; ++i)
  16.         if(path[i] == '/' || path[i] == '\\')
  17.             lastslash = i + 1;
  18.  
  19.     return path + lastslash;
  20. }
  21.  
  22. static int print_usage(const char * argv0)
  23. {
  24.     argv0 = filepath_to_filename(argv0);
  25.     fprintf(stderr, "%s - convert image to png using stb\n", argv0);
  26.     fprintf(stderr, "Usage: %s input.ext [output.png]\n", argv0);
  27.     return 1;
  28. }
  29.  
  30. static int print_file_error(const char * msg, const char * filename)
  31. {
  32.     fprintf(stderr, "%s for '%s'\n", msg, filename);
  33.     return 1;
  34. }
  35.  
  36. static int resave_image(const char * input, const char * output)
  37. {
  38.     int w, h, comp;
  39.     unsigned char * data;
  40.     int writeresult;
  41.  
  42.     data = stbi_load(input, &w, &h, &comp, 0);
  43.     if(data == NULL)
  44.         return print_file_error("stbi_load returned NULL", input);
  45.  
  46.     writeresult = stbi_write_png(output, w, h, comp, data, 0);
  47.     stbi_image_free(data);
  48.     if(writeresult == 0)
  49.         return print_file_error("stbi_write_png returned 0", output);
  50.  
  51.     return 0;
  52. }
  53.  
  54. static const char * make_outpath(const char * inpath)
  55. {
  56.     char * outpath = (char *)malloc(strlen(inpath) + 10);
  57.     if(!outpath)
  58.         return NULL;
  59.  
  60.     strcpy(outpath, inpath);
  61.     if(strchr(outpath, '.'))
  62.         (*strchr(outpath, '.')) = '\0';
  63.  
  64.     strcat(outpath, ".png");
  65.     return outpath;
  66. }
  67.  
  68. int main(int argc, char ** argv)
  69. {
  70.     int retcode = 0;
  71.     const char * outpath;
  72.  
  73.     if(argc != 2 && argc != 3)
  74.         return print_usage(argv[0]);
  75.  
  76.     if(argc == 2)
  77.     {
  78.         outpath = make_outpath(argv[1]);
  79.         if(!outpath)
  80.         {
  81.             fputs("malloc failed\n", stderr);
  82.             return 1;
  83.         }
  84.     }
  85.     else
  86.     {
  87.         outpath = argv[2];
  88.     }
  89.  
  90.     retcode = resave_image(argv[1], outpath);
  91.     if(argc == 2)
  92.         free((void*)outpath);
  93.  
  94.     return retcode;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement