Skip to content

Instantly share code, notes, and snippets.

@Dan-Q
Created December 12, 2018 15:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Dan-Q/674fbb5fef547432b7a5c9819701889a to your computer and use it in GitHub Desktop.
Convert a (small!) PNG image into JS/CSS that 'draws' the image in a Firefox/Chrome debug console.
#!/usr/bin/env ruby
# Bundler/Gemfile (inline mode)
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'chunky_png'
end
# Check for PNG file passed at command line or error out
if !ARGV[0]
puts 'Syntax: ./consolepic.rb your-png-file.png'
exit
end
# Convenience function: encodes a number as a string suitable for use as a JS variable
JS_VAR_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.freeze
def variablify(n)
return "a" if n == 0
result = ''
while n > 0
result = "#{JS_VAR_CHARS[n % JS_VAR_CHARS.length]}#{result}"
n /= JS_VAR_CHARS.length
end
result
end
# Load requested PNG file
img = ChunkyPNG::Image.from_file(ARGV[0])
# Store everything we need as we go along
colors = {}
pixels = []
# Loop through each pixel and gets its RGBA color
img.dimension.height.times do |i|
pixels << []
img.dimension.width.times do |j|
this_pixel = [ChunkyPNG::Color.r(img[j,i]), ChunkyPNG::Color.g(img[j,i]), ChunkyPNG::Color.b(img[j,i]), ChunkyPNG::Color.a(img[j,i])]
colors[img[j,i]] = this_pixel
pixels.last << [img[j,i], 1]
end
end
# Compress consecutive strings of alike pixels
pixels.length.times do |i|
pixels[i].length.times do |j|
(pixels[i].length-1).times do |k|
pixels[i][k][1], pixels[i][k+1][1] = (pixels[i][k][1]+pixels[i][k+1][1]), 0 if pixels[i][k][0]==pixels[i][k+1][0]
end
pixels[i].delete_if{|a|a[1]==0}
end
end
# Write some Javascript
print 'const '
print colors.map{|key, value| "#{variablify(key)}='background:rgba(#{value.join(',')});'"}.join(', ')
puts ';'
print 'console.log('
print pixels.flat_map{|row|
row.map{|block| "'%c#{' '*block[1]}'"}.join('+')
}.join("+\"\\n\"+\n ")
print ",\n "
print pixels.flat_map{|row|
row.map{|block| variablify(block[0])}.join(', ')
}.join(",\n ")
puts ');'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment