cammy/bin/png.c
2016-07-06 17:12:47 -05:00

95 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <cammy/image.h>
#include "pnglite.h"
#include "png.h"
int cammy_png_save(const char *file,
void *buf,
size_t width,
size_t height,
int depth,
int format) {
png_t *png;
png_init(malloc, free);
if ((png = malloc(sizeof(*png))) == NULL) {
goto error_malloc_png;
}
if (png_open_file_write(png, file) < 0) {
goto error_png_open_file_write;
}
if (png_set_data(png, width, height, depth, format, buf) < 0) {
goto error_png_set_data;
}
png_close_file(png);
free(png);
return 0;
error_png_set_data:
png_close_file(png);
error_png_open_file_write:
free(png);
error_malloc_png:
return -1;
}
uint8_t *cammy_png_load(const char *file,
size_t *width,
size_t *height,
int *depth) {
png_t *png;
uint8_t *buf;
png_init(malloc, free);
if ((png = malloc(sizeof(*png))) == NULL) {
goto error_malloc_png;
}
if (png_open_file_read(png, file) < 0) {
goto error_png_open_file_read;
}
*width = png->width;
*height = png->height;
*depth = png->bpp;
if ((buf = malloc(*width * *height * *depth)) == NULL) {
goto error_malloc_buf;
}
if (png_get_data(png, buf) < 0) {
goto error_png_get_data;
}
png_close_file(png);
free(png);
return buf;
error_png_get_data:
free(buf);
error_malloc_buf:
png_close_file(png);
error_png_open_file_read:
free(png);
error_malloc_png:
return NULL;
}