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