-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimage.c
79 lines (65 loc) · 2.02 KB
/
image.c
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
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <endian.h>
#include <jpeglib.h>
#include <jerror.h>
#include <cairo.h>
#include "image.h"
static cairo_surface_t *load_jpeg(const char* filename)
{
struct jpeg_decompress_struct info;
struct jpeg_error_mgr err;
cairo_surface_t *surface;
uint8_t *rowptr[1];
FILE* file;
file = fopen(filename, "rb");
if (!file) {
fprintf(stderr, "open %s: %s\n", filename, strerror(errno));
exit(1);
}
info.err = jpeg_std_error(&err);
jpeg_create_decompress(&info);
jpeg_stdio_src(&info, file);
jpeg_read_header(&info, TRUE);
#if __BYTE_ORDER == __LITTLE_ENDIAN
info.out_color_space = JCS_EXT_BGRX;
#else
info.out_color_space = JCS_EXT_XRGB;
#endif
jpeg_start_decompress(&info);
surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, /* 32bpp, native endian */
info.output_width,
info.output_height);
if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) {
fprintf(stderr, "cairo_image_surface_create failed\n");
exit(1);
}
while (info.output_scanline < info.output_height) {
rowptr[0] = (uint8_t *)cairo_image_surface_get_data(surface) +
cairo_image_surface_get_stride(surface) * info.output_scanline;
jpeg_read_scanlines(&info, rowptr, 1);
}
jpeg_finish_decompress(&info);
fclose(file);
return surface;
}
cairo_surface_t *load_image(const char* filename)
{
const char *ext = strrchr(filename, '.');
if (!ext) {
fprintf(stderr, "no file extension\n");
exit(1);
}
if (strcasecmp(ext, ".jpeg") == 0 ||
strcasecmp(ext, ".jpg") == 0)
return load_jpeg(filename);
if (strcasecmp(ext, ".png") == 0)
return cairo_image_surface_create_from_png(filename);
fprintf(stderr, "unknown file extension: \"%s\"\n", ext);
exit(1);
}