aboutsummaryrefslogtreecommitdiffstats
path: root/src/imagemagick.c
blob: ada2f6e70b66682770d1aac1519a35ee7ff3dfa8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#define _GNU_SOURCE

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#include "meh.h"

struct image *imagemagick_open(FILE *f){
	int tmpfd[2];
	if(pipe(tmpfd)){
		perror("pipe");
		exit(EXIT_FAILURE);
	}

	int pid;
	if(!(pid = fork())){
		close(tmpfd[0]);
		int origfd = fileno(f);
		if(lseek(origfd, 0, SEEK_SET) != 0){
			perror("lseek");
			exit(EXIT_FAILURE);
		}

		char *argv[6];

		argv[0] = "convert";
		argv[1] = "-depth";
		argv[2] = "255";
		asprintf(&argv[3], "fd:%i", origfd);
		asprintf(&argv[4], "ppm:fd:%i", tmpfd[1]);
		argv[5] = NULL;

#ifdef NDEBUG
		/* STFU OMFG */
		freopen("/dev/null", "w", stdout);
		freopen("/dev/null", "w", stderr);
#endif

		execvp(argv[0], argv);

		perror("exec");
		exit(EXIT_FAILURE);
	}else{
		close(tmpfd[1]);
		FILE *ftmp;
		if(!(ftmp = fdopen(tmpfd[0], "rb"))){
			perror("fopen");
			exit(EXIT_FAILURE);
		}
		struct image *img = netpbm.open(ftmp);
		if(!img)
			return NULL;
		fclose(f);
		return img;
	}
}

struct imageformat imagemagick = {
	imagemagick_open,
	NULL,
	NULL,
	NULL
};