]> git.lizzy.rs Git - tga_encoder.git/blob - init.lua
Add data encoding
[tga_encoder.git] / init.lua
1 tga_encoder = {}
2
3 local image = setmetatable({}, {
4         __call = function(self, ...)
5                 local t = setmetatable({}, {__index = image})
6                 t:constructor(...)
7                 return t
8         end,
9 })
10
11 function image:constructor(pixels)
12         self.bytes = {}
13         self.pixels = pixels
14         self.width = #pixles[1]
15         self.height = #pixels
16
17         self:encode()
18 end
19
20 function image:write(size, value)
21         -- TGA uses little endian encoding
22         local l = #self.bytes
23         for i = 1, size do
24                 local byte = value % 256
25                 value = value - byte
26                 value = value / 256
27                 self.bytes[l + i] = byte
28         end
29 end
30
31 function image:encode_colormap_spec()
32         -- first entry index
33         self:write(2, 0)
34         -- number of entries
35         self:write(2, 0)
36         -- number of bits per pixel
37         self:write(1, 0)
38 end
39
40 function image:encode_image_spec()
41         -- X- and Y- origin
42         self:write(2, 0)
43         self:write(2, 0)
44         -- width and height
45         self:write(2, width)
46         self:write(2, height)
47         -- pixel depth
48         self:write(1, 24)
49         -- image descriptor
50         self:write(1, 0)
51 end
52
53 function image:encode_header()
54         -- id length
55         self:write(1, 0) -- no image id info
56         -- color map type
57         self:write(1, 0) -- no color map
58         -- image type
59         self:write(1, 2) -- uncompressed true-color image
60         -- color map specification
61         self:encode_colormap_spec()
62         -- image specification
63         self:encode_image_spec()
64 end
65
66 function image:encode_data()
67         for _, row in ipairs(self.pixels) do
68                 for _, pixel in ipairs(row) do
69                         self:write(1, row[3])
70                         self:write(1, row[2])
71                         self:write(1, row[1])
72                 end
73         end
74 end
75
76 function image:encode()
77         -- encode header
78         self:encode_header()
79         -- no color map and image id data
80         -- encode data
81         self:encode_data()
82         -- no extension area or file footer
83 end
84
85 function image:save(filename)
86         self.data = self.data or string.char(unpack(self.bytes))
87         local f = assert(io.open(filename))
88         f:write(data)
89         f:close()
90 end
91
92 tga_encoder.image = image