prog.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include<lua.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<png.h>
  5. #include<string.h>
  6. #if !defined(_MSC_VER)
  7. #include<unistd.h>
  8. #endif
  9. static void *l_alloc (void *ud, void *ptr, size_t osize,
  10. size_t nsize) {
  11. (void)ud;
  12. (void)osize;
  13. if (nsize == 0) {
  14. free(ptr);
  15. return NULL;
  16. } else {
  17. return realloc(ptr, nsize);
  18. }
  19. }
  20. void open_image(const char *fname) {
  21. png_image image;
  22. memset(&image, 0, (sizeof image));
  23. image.version = PNG_IMAGE_VERSION;
  24. if(png_image_begin_read_from_file(&image, fname) != 0) {
  25. png_bytep buffer;
  26. image.format = PNG_FORMAT_RGBA;
  27. buffer = malloc(PNG_IMAGE_SIZE(image));
  28. if(png_image_finish_read(&image, NULL, buffer, 0, NULL) != 0) {
  29. printf("Image %s read failed: %s\n", fname, image.message);
  30. }
  31. // png_free_image(&image);
  32. free(buffer);
  33. } else {
  34. printf("Image %s open failed: %s", fname, image.message);
  35. }
  36. }
  37. int printer(lua_State *l) {
  38. if(!lua_isstring(l, 1)) {
  39. fprintf(stderr, "Incorrect call.\n");
  40. return 0;
  41. }
  42. open_image(lua_tostring(l, 1));
  43. return 0;
  44. }
  45. int main(int argc, char **argv) {
  46. lua_State *l = lua_newstate(l_alloc, NULL);
  47. if(!l) {
  48. printf("Lua state allocation failed.\n");
  49. return 1;
  50. }
  51. lua_register(l, "printer", printer);
  52. lua_getglobal(l, "printer");
  53. lua_pushliteral(l, "foobar.png");
  54. lua_call(l, 1, 0);
  55. lua_close(l);
  56. return 0;
  57. }