This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
nitrogenfingers's profile picture

[UTILITY] ASCII Image -> Table Converter

Started by nitrogenfingers, 04 September 2012 - 01:27 AM
nitrogenfingers #1
Posted 04 September 2012 - 03:27 AM
This is a little program I wrote while I was messing with some ASCII art. Because I tend to print ASCII images dynamically, in different parts of the screen I usually have to put the image in a table and write a function to print it. This however means I have to add the lua syntax- quote marks to each line and escaping out bad characters. For big images, and for lots of images, it's annoying.

So I wrote this little utility to do it for me. I thought someone might find it useful so here it is:




local image = { }
local args = {...}

--Takes in the relative path
function readFromFile(path)
  if not fs.exists(shell.resolve(".").."/"..path) then return end
  local file = io.open(shell.resolve(".").."/"..path, "r")
  local fline = file:read()
  local inc = 1
  while fline do
	table.insert(image, fline)
	fline = file:read()
  end  
  file:close()
end

function processImage()
for i=1,#image do
for x=1,#image[i] do
local char = string.sub(image[i], x, x)
if char == "\\" or char == "\"" then
image[i] = string.sub(image[i], 1, x-1).."\\"..string.sub(image[i], x, #image[i])
x=x+1
end
end
image[i] = "\""..image[i].."\";\n"
end
image[1] = "{\n"..image[1]
image[#image] = image[#image].."}"
end

function writeToFile(path)
  local file = io.open(shell.resolve(".").."/"..path, "w")
  for i=1,#image do
file:write(image[i])
  end
  file:close()
end

if #args == 0 then
print("Usage: converter [filepath]")
return
end

readFromFile(args[1])
processImage()
writeToFile(args[1])
print("Image converted for table import.")

If for example you put in this image:


  /\
  ||
  ||
  ||
  /\
o====o
  ||
  __

Feeding it in to the converter would produce this output:


{
"  /\\";
"  ||";
"  ||";
"  ||";
"  /\\";
"o====o";
"  ||";
"  __";
}

Pretty specialized little program but especially if you're working with a lot of images, or using a JPEG/PNG/GIF -> ASCII converter this could be handy.
Cranium #2
Posted 04 September 2012 - 05:18 AM
Wow, i really like this! I might have to use this on my next project.
Exerro #3
Posted 04 September 2012 - 03:19 PM
i use something like this in my paint program…how do you draw the ascii art in the first place? do you do it in game or out?
nitrogenfingers #4
Posted 04 September 2012 - 11:42 PM
I usually just open up a text file and try to draw it. I'm not an artist, so my attempts are pretty unimpressive (please artists- talk to me!). I've had a go at generating some ASCII art too but at low resolutions it looks terrible.