1 /* Load an ICC profile for embedding in an output file
2    Copyright (C) 2017 Aaron Muir Hamilton <aaron@correspondwith.me>
3 
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 */
17 
18 #include "../include/sane/config.h"
19 
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <sys/stat.h>
23 
24 void *
sanei_load_icc_profile(const char * path,size_t * size)25 sanei_load_icc_profile (const char *path, size_t *size)
26 {
27   FILE *fd = NULL;
28   size_t stated_size = 0;
29   void *profile = NULL;
30   struct stat s;
31 
32   fd = fopen(path, "r");
33 
34   if (!fd)
35   {
36     fprintf(stderr, "Could not open ICC profile %s\n", path);
37   }
38   else
39   {
40     fstat(fileno(fd), &s);
41     stated_size = 16777216 * fgetc(fd) + 65536 * fgetc(fd) + 256 * fgetc(fd) + fgetc(fd);
42     rewind(fd);
43 
44     if (stated_size > (size_t) s.st_size)
45     {
46       fprintf(stderr, "Ignoring ICC profile because file %s is shorter than the profile\n", path);
47     }
48     else
49     {
50       profile = malloc(stated_size);
51 
52       if (fread(profile, stated_size, 1, fd) != 1)
53       {
54         fprintf(stderr, "Error reading ICC profile %s\n", path);
55         free(profile);
56       }
57       else
58       {
59         fclose(fd);
60         *size = stated_size;
61         return profile;
62       }
63     }
64     fclose(fd);
65   }
66   return NULL;
67 }
68