├── Image2cGUI.py
├── LICENSE
├── Makefile
├── README.md
├── badger.gif
├── dist
├── MacOS
│ ├── Image2cGUI
│ ├── app_icon.ico
│ └── image_to_c
└── Windows
│ ├── GUI.png
│ ├── Image2cGUI.exe
│ ├── app_icon.ico
│ ├── image_to_c32.exe
│ └── image_to_c64.exe
├── main.c
└── screenshot.png
/Image2cGUI.py:
--------------------------------------------------------------------------------
1 | import subprocess
2 | import sys
3 | import os
4 | import ctypes
5 | import platform # <-- added
6 |
7 | # Function to check if a module is installed
8 | def is_module_installed(module_name):
9 | try:
10 | __import__(module_name)
11 | return True
12 | except ImportError:
13 | return False
14 |
15 | # Function to check if pip is available
16 | def is_pip_available():
17 | try:
18 | subprocess.run([sys.executable, "-m", "pip", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
19 | return True
20 | except:
21 | return False
22 |
23 | # Function to install a module using pip
24 | def install_module(module_name):
25 | subprocess.check_call([sys.executable, "-m", "pip", "install", module_name])
26 |
27 | # Check if tkinter is installed
28 | if not is_module_installed("tkinter"):
29 | if not is_pip_available():
30 | print("pip is not installed on your system.")
31 | print("Please download and install Python from https://www.python.org/downloads/windows/")
32 | sys.exit()
33 |
34 | user_input = input("tkinter is not installed. Would you like to install it now? (yes/no): ")
35 | if user_input.lower() == "yes":
36 | install_module("tkinter")
37 | else:
38 | print("Exiting as tkinter is required for the GUI.")
39 | sys.exit()
40 |
41 | import tkinter as tk
42 | from tkinter import filedialog, messagebox
43 |
44 | # Function to hide the console window
45 | def hide_console_window():
46 | ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
47 |
48 | def select_input_file():
49 | filepath = filedialog.askopenfilename(
50 | title="Select Input Image",
51 | filetypes=[
52 | ("Supported files", "*.png;*.jpeg;*.jpg;*.bmp;*.tiff;*.tif;*.gif;*.ppm;*.tga;*.cgm;*.cal;*.pcx"),
53 | ("All files", "*.*")
54 | ]
55 | )
56 | if filepath:
57 | input_file_var.set(filepath)
58 |
59 | def convert_image():
60 | input_file = input_file_var.get()
61 | if not input_file:
62 | return
63 |
64 | output_file = os.path.splitext(input_file)[0] + ".h"
65 |
66 | # Check OS and set command accordingly
67 | if platform.system() == "Windows":
68 | command = ["./image_to_c64"] if os.environ["PROCESSOR_ARCHITECTURE"] == "AMD64" else ["./image_to_c32"]
69 | elif platform.system() == "Darwin": # Darwin indicates macOS
70 | command = ["./image_to_c"]
71 | else:
72 | messagebox.showerror("Error", "Unsupported Operating System!")
73 | return
74 |
75 | if strip_var.get():
76 | command.append("--strip")
77 |
78 | command.append(input_file)
79 |
80 | result = subprocess.run(command, stdout=open(output_file, 'w'))
81 |
82 | if result.returncode == 0:
83 | messagebox.showinfo("Success", f"Image conversion successful! Output saved to: {output_file}")
84 | else:
85 | messagebox.showerror("Error", "Image conversion failed!")
86 |
87 | app = tk.Tk()
88 | app.title("Image to C")
89 | app.iconbitmap('app_icon.ico')
90 |
91 | input_file_var = tk.StringVar()
92 |
93 | input_frame = tk.Frame(app)
94 | input_frame.pack(pady=20, padx=20, fill=tk.X)
95 |
96 | input_label = tk.Label(input_frame, text="Input File:")
97 | input_label.pack(side=tk.LEFT)
98 |
99 | input_entry = tk.Entry(input_frame, textvariable=input_file_var, width=40)
100 | input_entry.pack(side=tk.LEFT, padx=10, expand=True, fill=tk.X)
101 |
102 | input_button = tk.Button(input_frame, text="Browse", command=select_input_file)
103 | input_button.pack(side=tk.LEFT)
104 |
105 | strip_var = tk.IntVar()
106 | strip_checkbox = tk.Checkbutton(app, text="Strip", variable=strip_var)
107 | strip_checkbox.pack(pady=10)
108 |
109 | convert_button = tk.Button(app, text="Convert", command=convert_image)
110 | convert_button.pack(pady=20)
111 |
112 | # Hide the console window (only for Windows)
113 | if platform.system() == "Windows":
114 | hide_console_window()
115 |
116 | # Center the window on the screen
117 | def center_window():
118 | app.update_idletasks()
119 | window_width = app.winfo_width()
120 | window_height = app.winfo_height()
121 | screen_width = app.winfo_screenwidth()
122 | screen_height = app.winfo_screenheight()
123 | x = (screen_width / 2) - (window_width / 2)
124 | y = (screen_height / 2) - (window_height / 2)
125 | app.geometry(f'+{int(x)}+{int(y)}')
126 |
127 | center_window()
128 | # Start the tkinter main loop
129 | app.mainloop()
130 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2020 BitBank Software, Inc. All rights reserved.
2 |
3 | Apache License
4 | Version 2.0, January 2004
5 | http://www.apache.org/licenses/
6 |
7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8 |
9 | 1. Definitions.
10 |
11 | "License" shall mean the terms and conditions for use, reproduction,
12 | and distribution as defined by Sections 1 through 9 of this document.
13 |
14 | "Licensor" shall mean the copyright owner or entity authorized by
15 | the copyright owner that is granting the License.
16 |
17 | "Legal Entity" shall mean the union of the acting entity and all
18 | other entities that control, are controlled by, or are under common
19 | control with that entity. For the purposes of this definition,
20 | "control" means (i) the power, direct or indirect, to cause the
21 | direction or management of such entity, whether by contract or
22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
23 | outstanding shares, or (iii) beneficial ownership of such entity.
24 |
25 | "You" (or "Your") shall mean an individual or Legal Entity
26 | exercising permissions granted by this License.
27 |
28 | "Source" form shall mean the preferred form for making modifications,
29 | including but not limited to software source code, documentation
30 | source, and configuration files.
31 |
32 | "Object" form shall mean any form resulting from mechanical
33 | transformation or translation of a Source form, including but
34 | not limited to compiled object code, generated documentation,
35 | and conversions to other media types.
36 |
37 | "Work" shall mean the work of authorship, whether in Source or
38 | Object form, made available under the License, as indicated by a
39 | copyright notice that is included in or attached to the work
40 | (an example is provided in the Appendix below).
41 |
42 | "Derivative Works" shall mean any work, whether in Source or Object
43 | form, that is based on (or derived from) the Work and for which the
44 | editorial revisions, annotations, elaborations, or other modifications
45 | represent, as a whole, an original work of authorship. For the purposes
46 | of this License, Derivative Works shall not include works that remain
47 | separable from, or merely link (or bind by name) to the interfaces of,
48 | the Work and Derivative Works thereof.
49 |
50 | "Contribution" shall mean any work of authorship, including
51 | the original version of the Work and any modifications or additions
52 | to that Work or Derivative Works thereof, that is intentionally
53 | submitted to Licensor for inclusion in the Work by the copyright owner
54 | or by an individual or Legal Entity authorized to submit on behalf of
55 | the copyright owner. For the purposes of this definition, "submitted"
56 | means any form of electronic, verbal, or written communication sent
57 | to the Licensor or its representatives, including but not limited to
58 | communication on electronic mailing lists, source code control systems,
59 | and issue tracking systems that are managed by, or on behalf of, the
60 | Licensor for the purpose of discussing and improving the Work, but
61 | excluding communication that is conspicuously marked or otherwise
62 | designated in writing by the copyright owner as "Not a Contribution."
63 |
64 | "Contributor" shall mean Licensor and any individual or Legal Entity
65 | on behalf of whom a Contribution has been received by Licensor and
66 | subsequently incorporated within the Work.
67 |
68 | 2. Grant of Copyright License. Subject to the terms and conditions of
69 | this License, each Contributor hereby grants to You a perpetual,
70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71 | copyright license to reproduce, prepare Derivative Works of,
72 | publicly display, publicly perform, sublicense, and distribute the
73 | Work and such Derivative Works in Source or Object form.
74 |
75 | 3. Grant of Patent License. Subject to the terms and conditions of
76 | this License, each Contributor hereby grants to You a perpetual,
77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78 | (except as stated in this section) patent license to make, have made,
79 | use, offer to sell, sell, import, and otherwise transfer the Work,
80 | where such license applies only to those patent claims licensable
81 | by such Contributor that are necessarily infringed by their
82 | Contribution(s) alone or by combination of their Contribution(s)
83 | with the Work to which such Contribution(s) was submitted. If You
84 | institute patent litigation against any entity (including a
85 | cross-claim or counterclaim in a lawsuit) alleging that the Work
86 | or a Contribution incorporated within the Work constitutes direct
87 | or contributory patent infringement, then any patent licenses
88 | granted to You under this License for that Work shall terminate
89 | as of the date such litigation is filed.
90 |
91 | 4. Redistribution. You may reproduce and distribute copies of the
92 | Work or Derivative Works thereof in any medium, with or without
93 | modifications, and in Source or Object form, provided that You
94 | meet the following conditions:
95 |
96 | (a) You must give any other recipients of the Work or
97 | Derivative Works a copy of this License; and
98 |
99 | (b) You must cause any modified files to carry prominent notices
100 | stating that You changed the files; and
101 |
102 | (c) You must retain, in the Source form of any Derivative Works
103 | that You distribute, all copyright, patent, trademark, and
104 | attribution notices from the Source form of the Work,
105 | excluding those notices that do not pertain to any part of
106 | the Derivative Works; and
107 |
108 | (d) If the Work includes a "NOTICE" text file as part of its
109 | distribution, then any Derivative Works that You distribute must
110 | include a readable copy of the attribution notices contained
111 | within such NOTICE file, excluding those notices that do not
112 | pertain to any part of the Derivative Works, in at least one
113 | of the following places: within a NOTICE text file distributed
114 | as part of the Derivative Works; within the Source form or
115 | documentation, if provided along with the Derivative Works; or,
116 | within a display generated by the Derivative Works, if and
117 | wherever such third-party notices normally appear. The contents
118 | of the NOTICE file are for informational purposes only and
119 | do not modify the License. You may add Your own attribution
120 | notices within Derivative Works that You distribute, alongside
121 | or as an addendum to the NOTICE text from the Work, provided
122 | that such additional attribution notices cannot be construed
123 | as modifying the License.
124 |
125 | You may add Your own copyright statement to Your modifications and
126 | may provide additional or different license terms and conditions
127 | for use, reproduction, or distribution of Your modifications, or
128 | for any such Derivative Works as a whole, provided Your use,
129 | reproduction, and distribution of the Work otherwise complies with
130 | the conditions stated in this License.
131 |
132 | 5. Submission of Contributions. Unless You explicitly state otherwise,
133 | any Contribution intentionally submitted for inclusion in the Work
134 | by You to the Licensor shall be under the terms and conditions of
135 | this License, without any additional terms or conditions.
136 | Notwithstanding the above, nothing herein shall supersede or modify
137 | the terms of any separate license agreement you may have executed
138 | with Licensor regarding such Contributions.
139 |
140 | 6. Trademarks. This License does not grant permission to use the trade
141 | names, trademarks, service marks, or product names of the Licensor,
142 | except as required for reasonable and customary use in describing the
143 | origin of the Work and reproducing the content of the NOTICE file.
144 |
145 | 7. Disclaimer of Warranty. Unless required by applicable law or
146 | agreed to in writing, Licensor provides the Work (and each
147 | Contributor provides its Contributions) on an "AS IS" BASIS,
148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149 | implied, including, without limitation, any warranties or conditions
150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151 | PARTICULAR PURPOSE. You are solely responsible for determining the
152 | appropriateness of using or redistributing the Work and assume any
153 | risks associated with Your exercise of permissions under this License.
154 |
155 | 8. Limitation of Liability. In no event and under no legal theory,
156 | whether in tort (including negligence), contract, or otherwise,
157 | unless required by applicable law (such as deliberate and grossly
158 | negligent acts) or agreed to in writing, shall any Contributor be
159 | liable to You for damages, including any direct, indirect, special,
160 | incidental, or consequential damages of any character arising as a
161 | result of this License or out of the use or inability to use the
162 | Work (including but not limited to damages for loss of goodwill,
163 | work stoppage, computer failure or malfunction, or any and all
164 | other commercial damages or losses), even if such Contributor
165 | has been advised of the possibility of such damages.
166 |
167 | 9. Accepting Warranty or Additional Liability. While redistributing
168 | the Work or Derivative Works thereof, You may choose to offer,
169 | and charge a fee for, acceptance of support, warranty, indemnity,
170 | or other liability obligations and/or rights consistent with this
171 | License. However, in accepting such obligations, You may act only
172 | on Your own behalf and on Your sole responsibility, not on behalf
173 | of any other Contributor, and only if You agree to indemnify,
174 | defend, and hold each Contributor harmless for any liability
175 | incurred by, or claims asserted against, such Contributor by reason
176 | of your accepting any such warranty or additional liability.
177 |
178 | END OF TERMS AND CONDITIONS
179 |
180 | APPENDIX: How to apply the Apache License to your work.
181 |
182 | To apply the Apache License to your work, attach the following
183 | boilerplate notice, with the fields enclosed by brackets "[]"
184 | replaced with your own identifying information. (Don't include
185 | the brackets!) The text should be enclosed in the appropriate
186 | comment syntax for the file format. We also recommend that a
187 | file or class name and description of purpose be included on the
188 | same "printed page" as the copyright notice for easier
189 | identification within third-party archives.
190 |
191 | Copyright [yyyy] [name of copyright owner]
192 |
193 | Licensed under the Apache License, Version 2.0 (the "License");
194 | you may not use this file except in compliance with the License.
195 | You may obtain a copy of the License at
196 |
197 | http://www.apache.org/licenses/LICENSE-2.0
198 |
199 | Unless required by applicable law or agreed to in writing, software
200 | distributed under the License is distributed on an "AS IS" BASIS,
201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202 | See the License for the specific language governing permissions and
203 | limitations under the License.
204 |
205 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | CFLAGS=-c -Wall -O0
2 | LIBS =
3 |
4 | all: image_to_c
5 |
6 | image_to_c: main.o
7 | $(CC) main.o $(LIBS) -o image_to_c
8 |
9 | main.o: main.c
10 | $(CC) $(CFLAGS) main.c
11 |
12 | clean:
13 | rm -rf *.o image_to_c
14 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | image_to_c
2 | ----------
3 | Added GUI wrapper. For windows run 'Image2cGUI.exe' and for Mac run 'Image2cGUI'.
4 |
5 |
6 | A command line tool for turning binary image files into C source code. The output is an array of unsigned chars and is sent to stdout. Included are comments detailing the image type, size and other details.
7 |
8 |
9 |
10 | Why did you write it?
11 | My existing tool (bin_to_c) is similar in that it generates C arrays to compile file data directly into a project. I have used this tool to create many .H files to include with my projects, but the filename alone isn't enough to know the details of the image file contained in the data. Instead of manually adding this information to each file, I came up with the idea of combining my imageinfo tool with the bin_to_c tool to make something even more useful.
12 | What does the output look like?
13 | Here's an example of a before and after of what this new tool does:
14 |
15 | It turns this type of file:
16 | 
17 |
18 | Into this type of file:
19 | 
20 |
21 | What image file types does it support?
22 |
23 | PNG, JPEG, BMP, TIFF, GIF, PPM, TARGA, JEDMICS, CALS and PCX
24 |
25 | What happens for unrecognized files?
26 | If the file type is not known, it will generate the same C output, but without additional info.
27 |
28 | New Feature
29 | I just added the ability to write only the image data and strip off the header/metadata. Use the --strip option on TIFF and BMP files.
30 | Example: ./image_to_c --strip input.bmp > output.h
31 | This will only write the pixel data (compressed or not) to the output file
32 |
33 | If you find this code useful, please consider sending a donation or becoming a Github sponsor.
34 |
35 | [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=SR4F44J2UR8S4)
36 |
37 |
--------------------------------------------------------------------------------
/badger.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/badger.gif
--------------------------------------------------------------------------------
/dist/MacOS/Image2cGUI:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/MacOS/Image2cGUI
--------------------------------------------------------------------------------
/dist/MacOS/app_icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/MacOS/app_icon.ico
--------------------------------------------------------------------------------
/dist/MacOS/image_to_c:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/MacOS/image_to_c
--------------------------------------------------------------------------------
/dist/Windows/GUI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/Windows/GUI.png
--------------------------------------------------------------------------------
/dist/Windows/Image2cGUI.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/Windows/Image2cGUI.exe
--------------------------------------------------------------------------------
/dist/Windows/app_icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/Windows/app_icon.ico
--------------------------------------------------------------------------------
/dist/Windows/image_to_c32.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/Windows/image_to_c32.exe
--------------------------------------------------------------------------------
/dist/Windows/image_to_c64.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bitbank2/image_to_c/be37230ba623b2cdca9a798058ef71bc936570f0/dist/Windows/image_to_c64.exe
--------------------------------------------------------------------------------
/main.c:
--------------------------------------------------------------------------------
1 | //
2 | // image_to_c - convert binary image files into c-compatible data tables
3 | //
4 | // Written by Larry Bank
5 | // Copyright (c) 2020 BitBank Software, Inc.
6 | // Change history
7 | // 12/2/20 - Started the project
8 | //
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 | #define TEMP_BUF_SIZE 4096
15 | #define DEFAULT_READ_SIZE 256
16 | #define MAX_TAGS 256
17 | #define TIFF_TAGSIZE 12
18 |
19 | #define INTELSHORT(p) ((*p) + (*(p+1)<<8))
20 | #define INTELLONG(p) ((*p) + (*(p+1)<<8) + (*(p+2)<<16) + (*(p+3)<<24))
21 | #define MOTOSHORT(p) (((*(p))<<8) + (*(p+1)))
22 | #define MOTOLONG(p) (((*p)<<24) + ((*(p+1))<<16) + ((*(p+2))<<8) + (*(p+3)))
23 |
24 | #ifdef _WIN32
25 | #define PILIO_SLASH_CHAR '\\'
26 | #else
27 | #define PILIO_SLASH_CHAR '/'
28 | #endif
29 |
30 | typedef unsigned char BOOL;
31 |
32 | const char *szType[] = {"Unknown", "PNG","JFIF","Win BMP","OS/2 BMP","TIFF","GIF","Portable Pixmap","Targa","JEDMICS","CALS","PCX"};
33 | const char *szComp[] = {"Unknown", "Flate","JPEG","None","RLE","LZW","G3","G4","Packbits","Modified Huffman","Thunderscan RLE","JBIG (T.85)"};
34 | const char *szPhotometric[] = {"WhiteIsZero","BlackIsZero","RGB","Palette Color","Transparency Mask","CMYK","YCbCr","Unknown"};
35 | const char *szPlanar[] = {"Unknown","Chunky","Planar"};
36 |
37 | enum
38 | {
39 | FILETYPE_UNKNOWN = 0,
40 | FILETYPE_PNG,
41 | FILETYPE_JPEG,
42 | FILETYPE_BMP,
43 | FILETYPE_OS2BMP,
44 | FILETYPE_TIFF,
45 | FILETYPE_GIF,
46 | FILETYPE_PPM,
47 | FILETYPE_TARGA,
48 | FILETYPE_JEDMICS,
49 | FILETYPE_CALS,
50 | FILETYPE_PCX
51 | };
52 |
53 | enum
54 | {
55 | COMPTYPE_UNKNOWN = 0,
56 | COMPTYPE_FLATE,
57 | COMPTYPE_JPEG,
58 | COMPTYPE_NONE,
59 | COMPTYPE_RLE,
60 | COMPTYPE_LZW,
61 | COMPTYPE_G3,
62 | COMPTYPE_G4,
63 | COMPTYPE_PACKBITS,
64 | COMPTYPE_HUFFMAN,
65 | COMPTYPE_THUNDERSCAN,
66 | COMPTYPE_JBIG
67 | };
68 |
69 | FILE * ihandle;
70 | void MakeC(unsigned char *, int, int);
71 | void GetLeafName(char *fname, char *leaf);
72 | void FixName(char *name);
73 |
74 | unsigned short TIFFSHORT(unsigned char *p, BOOL bMotorola)
75 | {
76 | unsigned short s;
77 |
78 | if (bMotorola)
79 | s = *p * 0x100 + *(p+1);
80 | else
81 | s = *p + *(p+1)*0x100;
82 |
83 | return s;
84 | } /* TIFFSHORT() */
85 |
86 | uint32_t TIFFLONG(unsigned char *p, BOOL bMotorola)
87 | {
88 | uint32_t l;
89 |
90 | if (bMotorola)
91 | l = *p * 0x1000000 + *(p+1) * 0x10000 + *(p+2) * 0x100 + *(p+3);
92 | else
93 | l = *p + *(p+1) * 0x100 + *(p+2) * 0x10000 + *(p+3) * 0x1000000;
94 |
95 | return l;
96 | } /* TIFFLONG() */
97 |
98 | int TIFFVALUE(unsigned char *p, BOOL bMotorola)
99 | {
100 | int i, iType;
101 |
102 | iType = TIFFSHORT(p+2, bMotorola);
103 | /* If pointer to a list of items, must be a long */
104 | if (TIFFSHORT(p+4, bMotorola) > 1)
105 | iType = 4;
106 | switch (iType)
107 | {
108 | case 3: /* Short */
109 | i = TIFFSHORT(p+8, bMotorola);
110 | break;
111 | case 4: /* Long */
112 | case 7: // undefined (treat it as a long since it's usually a multibyte buffer)
113 | i = TIFFLONG(p+8, bMotorola);
114 | break;
115 | case 6: // signed byte
116 | i = (signed char)p[8];
117 | break;
118 | case 2: /* ASCII */
119 | case 5: /* Unsigned Rational */
120 | case 10: /* Signed Rational */
121 | i = TIFFLONG(p+8, bMotorola);
122 | break;
123 | default: /* to suppress compiler warning */
124 | i = 0;
125 | break;
126 | }
127 | return i;
128 |
129 | } /* TIFFVALUE() */
130 |
131 | int ParseNumber(unsigned char *buf, int *iOff, int iLength)
132 | {
133 | int i, iOffset;
134 |
135 | i = 0;
136 | iOffset = *iOff;
137 |
138 | while (iOffset < iLength && buf[iOffset] >= '0' && buf[iOffset] <= '9')
139 | {
140 | i *= 10;
141 | i += (int)(buf[iOffset++] - '0');
142 | }
143 | *iOff = iOffset+1; /* Skip ending char */
144 | return i;
145 |
146 | } /* ParseNumber() */
147 |
148 | //
149 | // CountGIFFrames
150 | //
151 | // Given a pointer to a multipage GIF image
152 | // This function will walk through the file and count the number
153 | // of frames present
154 | //
155 | int CountGIFFrames(unsigned char *cBuf, int iFileSize)
156 | {
157 | int iNumFrames;
158 | size_t iOff;
159 | int bDone = 0;
160 | int bExt;
161 | unsigned char c;
162 |
163 | iNumFrames = 0;
164 | iOff = 10;
165 | c = cBuf[iOff]; // get info bits
166 | iOff += 3; /* Skip flags, background color & aspect ratio */
167 | if (c & 0x80) /* Deal with global color table */
168 | {
169 | c &= 7; /* Get the number of colors defined */
170 | iOff += (2<= iFileSize) // problem
218 | {
219 | iNumFrames--; // possible corrupt data; stop
220 | bDone = 1;
221 | // *bTruncated = TRUE;
222 | continue;
223 | }
224 | /* Start of image data */
225 | c = cBuf[iOff+9]; /* Get the flags byte */
226 | iOff += 10; /* Skip image position and size */
227 | if (c & 0x80) /* Local color table */
228 | {
229 | c &= 7;
230 | iOff += (2< iFileSize) // past end of file, stop
238 | {
239 | iNumFrames--; // don't count this frame
240 | break; // last page is corrupted, don't use it
241 | }
242 | c = cBuf[iOff++]; /* Get length of next */
243 | }
244 | /* End of image data, check for more frames... */
245 | if ((iOff > iFileSize) || cBuf[iOff] == 0x3b)
246 | {
247 | bDone = 1; /* End of file has been reached */
248 | }
249 | else
250 | {
251 | iNumFrames++;
252 | }
253 | } /* while !bDone */
254 | return iNumFrames;
255 |
256 | } /* CountGIFFrames() */
257 | //
258 | // Returns the image data size
259 | //
260 | int ImageInfo(FILE *iHandle, int iFileSize, char *szInfo, int *iDataOff)
261 | {
262 | int i, j, k;
263 | int iBytes;
264 | int iFileType = FILETYPE_UNKNOWN;
265 | int iCompression = COMPTYPE_UNKNOWN;
266 | unsigned char cBuf[TEMP_BUF_SIZE]; // small buffer to load header info
267 | int iBpp = 0;
268 | int iWidth = 0;
269 | int iHeight = 0;
270 | int iOffset;
271 | int iMarker;
272 | int iPhotoMetric;
273 | int iPlanar;
274 | int iCount;
275 | int iDataSize = 0; // size of the compressed data
276 | unsigned char ucSubSample;
277 | BOOL bMotorola;
278 | char szOptions[256];
279 |
280 | szInfo[0] = 0; // start with null string
281 |
282 | // Detect the file type by its header
283 | iBytes = fread(cBuf, 1, DEFAULT_READ_SIZE, iHandle);
284 | if (iBytes < 64)
285 | return -1; // too small
286 | if (MOTOLONG(cBuf) == 0x89504e47) // PNG
287 | iFileType = FILETYPE_PNG;
288 | else if (cBuf[0] == 'B' && cBuf[1] == 'M') // BMP
289 | {
290 | if (cBuf[14] == 0x28) // Windows
291 | iFileType = FILETYPE_BMP;
292 | else
293 | iFileType = FILETYPE_OS2BMP;
294 | }
295 | else if (cBuf[0] == 0x0a && cBuf[1] < 0x6 && cBuf[2] == 0x01)
296 | {
297 | iFileType = FILETYPE_PCX;
298 | }
299 | else if (INTELLONG(cBuf) == 0x80 && (cBuf[36] == 4 || cBuf[36] == 6))
300 | {
301 | iFileType = FILETYPE_JEDMICS;
302 | }
303 | else if (INTELLONG(cBuf) == 0x64637273)
304 | {
305 | iFileType = FILETYPE_CALS;
306 | }
307 | else if ((MOTOLONG(cBuf) & 0xffffff00) == 0xffd8ff00) // JPEG
308 | iFileType = FILETYPE_JPEG;
309 | else if (MOTOLONG(cBuf) == 0x47494638 /*'GIF8'*/) // GIF
310 | iFileType = FILETYPE_GIF;
311 | else if ((cBuf[0] == 'I' && cBuf[1] == 'I') || (cBuf[0] == 'M' && cBuf[1] == 'M'))
312 | iFileType = FILETYPE_TIFF;
313 | else
314 | {
315 | i = MOTOLONG(cBuf) & 0xffff8080;
316 | if (i == 0x50360000 || i == 0x50350000 || i == 0x50340000) // Portable bitmap/graymap/pixmap
317 | iFileType = FILETYPE_PPM;
318 | }
319 | // Check for Truvision Targa
320 | i = cBuf[1] & 0xfe;
321 | j = cBuf[2];
322 | // make sure it is not a MPEG file (starts with 00 00 01 BA)
323 | if (MOTOLONG(cBuf) != 0x1ba && MOTOLONG(cBuf) != 0x1b3 && i == 0 && (j == 1 || j == 2 || j == 3 || j == 9 || j == 10 || j == 11))
324 | iFileType = FILETYPE_TARGA;
325 |
326 | if (iFileType == FILETYPE_UNKNOWN)
327 | {
328 | return -1;
329 | }
330 | szOptions[0] = '\0'; // info specific to each file type
331 | // Get info specific to each type of file
332 | switch (iFileType)
333 | {
334 | case FILETYPE_PCX:
335 | iWidth = 1 + INTELSHORT(&cBuf[8]) - INTELSHORT(&cBuf[4]);
336 | iHeight = 1 + INTELSHORT(&cBuf[10]) - INTELSHORT(&cBuf[6]);
337 | iCompression = COMPTYPE_PACKBITS;
338 | iBpp = cBuf[3] * cBuf[65];
339 | break;
340 |
341 | case FILETYPE_PNG:
342 | if (MOTOLONG(&cBuf[12]) == 0x49484452/*'IHDR'*/)
343 | {
344 | iWidth = MOTOLONG(&cBuf[16]);
345 | iHeight = MOTOLONG(&cBuf[20]);
346 | iCompression = COMPTYPE_FLATE;
347 | i = cBuf[24]; // bits per pixel
348 | j = cBuf[25]; // pixel type
349 | switch (j)
350 | {
351 | case 0: // grayscale
352 | case 3: // palette image
353 | iBpp = i;
354 | break;
355 | case 2: // RGB triple
356 | iBpp = i * 3;
357 | break;
358 | case 4: // grayscale + alpha channel
359 | iBpp = i * 2;
360 | break;
361 | case 6: // RGB + alpha
362 | iBpp = i * 4;
363 | break;
364 | }
365 | if (cBuf[28] == 1) // interlace flag
366 | strcpy(szOptions, ", Interlaced");
367 | else
368 | strcpy(szOptions, ", Not interlaced");
369 | }
370 | break;
371 | case FILETYPE_TARGA:
372 | iWidth = INTELSHORT(&cBuf[12]);
373 | iHeight = INTELSHORT(&cBuf[14]);
374 | iBpp = cBuf[16];
375 | if (cBuf[2] == 3 || cBuf[2] == 11) // monochrome
376 | iBpp = 1;
377 | if (cBuf[2] < 9)
378 | iCompression = COMPTYPE_NONE;
379 | else
380 | iCompression = COMPTYPE_RLE;
381 | break;
382 | case FILETYPE_PPM:
383 | if (cBuf[1] == '4')
384 | iBpp = 1;
385 | else if (cBuf[1] == '5')
386 | iBpp = 8;
387 | else if (cBuf[1] == '6')
388 | iBpp = 24;
389 | j = 2;
390 | while ((cBuf[j] == 0xa || cBuf[j] == 0xd) && j>4),(ucSubSample & 0xf));
513 | }
514 | break;
515 | case FILETYPE_GIF:
516 | iCompression = COMPTYPE_LZW;
517 | iWidth = INTELSHORT(&cBuf[6]);
518 | iHeight = INTELSHORT(&cBuf[8]);
519 | iBpp = (cBuf[10] & 7) + 1;
520 | if (cBuf[10] & 64) // interlace flag
521 | strcpy(szOptions, ", Interlaced");
522 | else
523 | strcpy(szOptions, ", Not interlaced");
524 | break;
525 | case FILETYPE_TIFF:
526 | bMotorola = (cBuf[0] == 'M'); // determine endianness of TIFF data
527 | i = TIFFLONG(&cBuf[4], bMotorola); // get first IFD offset
528 | fseek(iHandle, i, SEEK_SET);// read the entire tag directory
529 | iBytes = fread(cBuf, 1, MAX_TAGS*TIFF_TAGSIZE, iHandle);
530 | j = TIFFSHORT(cBuf, bMotorola); // get the tag count
531 | iOffset = 2; // point to start of TIFF tag directory
532 | // Some TIFF files don't specify everything, so set up some default values
533 | iBpp = 1;
534 | iPlanar = 1;
535 | iCompression = COMPTYPE_NONE;
536 | iPhotoMetric = 7; // if not specified, set to "unknown"
537 | // Each TIFF tag is made up of 12 bytes
538 | // byte 0-1: Tag value (short)
539 | // byte 2-3: data type (short)
540 | // byte 4-7: number of values (long)
541 | // byte 8-11: value or offset to list of values
542 | for (i=0; i 6)
596 | iPhotoMetric = 7; // unknown
597 | break;
598 | case 273: // strip offsets
599 | *iDataOff = TIFFVALUE(&cBuf[iOffset], bMotorola);
600 | break;
601 | case 279: // strip byte counts
602 | iDataSize = TIFFVALUE(&cBuf[iOffset], bMotorola);
603 | break;
604 | case 284: // planar/chunky
605 | iPlanar = TIFFVALUE(&cBuf[iOffset], bMotorola);
606 | if (iPlanar < 1 || iPlanar > 2) // unknown value
607 | iPlanar = 0; // unknown
608 | break;
609 | } // switch on tiff tag
610 | iOffset += TIFF_TAGSIZE;
611 | } // for each tag
612 | // sprintf(szOptions, ", Photometric = %s, Planar config = %s", szPhotometric[iPhotoMetric], szPlanar[iPlanar]);
613 | // break;
614 | } // switch
615 | sprintf(szInfo, "// %s, Compression=%s, Size: %d x %d, %d-Bpp\n", szType[iFileType], szComp[iCompression], iWidth, iHeight, iBpp);
616 | if (iFileType == FILETYPE_GIF) // see how many frames it has
617 | {
618 | // slight hack - load the file into memory
619 | uint8_t *pFile;
620 | char szTemp[32];
621 | int iFrames;
622 | pFile = malloc(iFileSize);
623 | if (pFile != NULL)
624 | {
625 | fseek(iHandle, 0, SEEK_SET);
626 | fread(pFile, 1, iFileSize, iHandle);
627 | iFrames = CountGIFFrames(pFile, iFileSize);
628 | free(pFile);
629 | sprintf(szTemp, "// %d frames\n//\n", iFrames);
630 | strcat(szInfo, szTemp);
631 | }
632 | }
633 | else
634 | {
635 | strcat(szInfo, "//\n"); // simple end of comment
636 | }
637 | return iDataSize;
638 | } /* ImageInfo() */
639 | //
640 | // Main program entry point
641 | //
642 | int main(int argc, char *argv[])
643 | {
644 | int iSize, iData;
645 | int bStrip = 0;
646 | unsigned char *p;
647 | int iStart = 1; // starting parameter for input name
648 | int iDataOff, iDataSize;
649 | char szLeaf[256];
650 | char szInfo[256];
651 |
652 | if (argc != 2 && argc != 3)
653 | {
654 | printf("image_to_c Copyright (c) 2020 BitBank Software, Inc.\n");
655 | printf("Written by Larry Bank\n\n");
656 | printf("Usage: image_to_c