Encode image only when saving it to a file

This commit is contained in:
Nils Dagsson Moskopp 2022-05-15 14:54:28 +02:00
parent 5640e19c94
commit 9bd1702d60
Signed by untrusted user who does not match committer: erlehmann
GPG Key ID: A3BC671C35191080
2 changed files with 14 additions and 13 deletions

View File

@ -39,7 +39,7 @@ for x = 1,6,1 do -- left to right
pixels[z][x] = color
end
end
tga_encoder.image(pixels, {colors="BW", pixel_depth=8}):save("gradients_8bpp.tga")
tga_encoder.image(pixels):save("gradients_8bpp.tga", {colors="BW", pixel_depth=8})
local pixels = {}
for x = 1,16,1 do -- left to right
@ -58,8 +58,9 @@ for x = 1,16,1 do -- left to right
pixels[z][x] = color
end
end
tga_encoder.image(pixels, {colors="RGB", pixel_depth=16}):save("gradients_16bpp.tga")
tga_encoder.image(pixels, {colors="RGB", pixel_depth=24}):save("gradients_24bpp.tga")
local gradients = tga_encoder.image(pixels)
gradients:save("gradients_16bpp.tga", {colors="RGB", pixel_depth=16})
gradients:save("gradients_24bpp.tga", {colors="RGB", pixel_depth=24})
local pixels = {}
for x = 1,512,1 do -- left to right
@ -81,4 +82,4 @@ for x = 1,512,1 do -- left to right
pixels[z][x] = color
end
end
tga_encoder.image(pixels, {colors="RGB", pixel_depth=24}):save("fractal_24bpp.tga")
tga_encoder.image(pixels):save("fractal_24bpp.tga", {colors="RGB", pixel_depth=24})

View File

@ -8,17 +8,10 @@ local image = setmetatable({}, {
end,
})
function image:constructor(pixels, properties)
local properties = properties or {}
properties.colors = properties.colors or "RGB"
properties.pixel_depth = properties.pixel_depth or 16
self.data = ""
function image:constructor(pixels)
self.pixels = pixels
self.width = #pixels[1]
self.height = #pixels
self:encode(properties)
end
function image:encode_colormap_spec()
@ -263,6 +256,7 @@ function image:encode_footer()
end
function image:encode(properties)
self.data = ""
self:encode_header(properties) -- header
-- no color map and image id data
self:encode_data(properties) -- encode data
@ -270,7 +264,13 @@ function image:encode(properties)
self:encode_footer() -- footer
end
function image:save(filename)
function image:save(filename, properties)
local properties = properties or {}
properties.colors = properties.colors or "RGB"
properties.pixel_depth = properties.pixel_depth or 16
self:encode(properties)
local f = assert(io.open(filename, "wb"))
f:write(self.data)
f:close()