emote2ss

Animated webp to spritesheets converting tool
git clone git://bsandro.tech/emote2ss
Log | Files | Refs | README | LICENSE

fileops.c (1547B)


      1 #define _POSIX_C_SOURCE 1
      2 
      3 #include <errno.h>
      4 #include <stdio.h>
      5 #include <sys/stat.h>
      6 #include "webp/decode.h"
      7 #include "webp/encode.h"
      8 #include "webp/demux.h"
      9 #include "fileops.h"
     10 #include "spritesheet.h"
     11 
     12 int FileRead(const char *filename, const uint8_t **data, size_t *size) {
     13 	assert(data != NULL);
     14 	assert(size != NULL);
     15 	*data = NULL;
     16 	*size = 0;
     17 	FILE *infile = fopen(filename, "rb");
     18 	assert(infile != NULL);
     19 	struct stat sb;
     20 	if (fstat(fileno(infile), &sb)==-1) {
     21 		fprintf(stderr, "error: %s\n", strerror(errno));
     22 		fclose(infile);
     23 		return -1;
     24 	}
     25 	if (!S_ISREG(sb.st_mode)) {
     26 		fprintf(stderr, "%s is not a regular file\n", filename);
     27 		fclose(infile);
     28 		return -1;
     29 	}
     30 
     31 	size_t fsize = sb.st_size;
     32 	printf("%s: %zu bytes\n", filename, fsize);
     33 	uint8_t *fdata = malloc(fsize+1);
     34 	assert(fdata != NULL);
     35 	fdata[fsize] = '\0';
     36 	int ok = (fread(fdata, fsize, 1, infile)==1);
     37 	fclose(infile);
     38 
     39 	if (!ok) {
     40 		fprintf(stderr, "cannot read file %s (%d)\n", filename, ok);
     41 		free(fdata);
     42 		return -1;
     43 	}
     44 	*data = fdata;
     45 	*size = fsize;
     46 	return 0;
     47 }
     48 
     49 void WebpWrite(const char *path, Animation *img, int cols) {
     50 	Spritesheet ss = SpritesheetGen(img, cols);
     51 	uint8_t *out;
     52 	FILE *fp = fopen(path, "wb");
     53 	assert(fp!=NULL);
     54 	size_t encoded = WebPEncodeLosslessRGBA(ss.data, ss.width, ss.height, ss.stride, &out);
     55 	// printf("size: %zu, encoded: %zu\n", img->width*img->height*sizeof(uint32_t), encoded);
     56 	assert(encoded!=0);
     57 	size_t written = fwrite(out, sizeof(uint8_t), encoded, fp);
     58 	assert(written==encoded);
     59 	WebPFree(out);
     60 	free(ss.data);
     61 }