Created
April 24, 2012 22:53
-
-
Save TheKidCoder/2484432 to your computer and use it in GitHub Desktop.
Simple Thor task to convert PNGs to Base64 strings. Also compresses them using pngcrush.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'thor' | |
require 'base64' | |
require 'clipboard' | |
module PNGUtils | |
def PNGUtils.crush(file_path) | |
crushed = "#{file_path}.crushed" | |
# `pngcrush -rem alla -reduce -brute "#{file_path}" "#{crushed}"` | |
output = IO.popen("pngcrush -rem alla -reduce -brute \"#{file_path}\" \"#{crushed}\"") | |
puts output.readlines | |
return crushed | |
end | |
def PNGUtils.encode(file_path) | |
string = Base64.encode64(File.read(file_path)).gsub(/\s+/, "") | |
return string | |
end | |
end | |
class Pngto64 < Thor | |
include PNGUtils | |
desc "single_file FILE_PATH", "Converts single PNG to Base64 and copies string to your clipboard." | |
def single_file(file_path) | |
#Crush PNG First | |
crushed = PNGUtils.crush(file_path) | |
#Encode crushed file to base64, copy to clipboard. | |
string = PNGUtils.encode(crushed) | |
Clipboard.copy string | |
#Delete the file created in by the crusher. | |
FileUtils.remove_file(crushed) | |
#Display the all clear - In Green Text! | |
puts "\e[1m\e[32mBase64 String is in your Clipboard!\e[0m" | |
end | |
desc "crush_64string [STRING]", "Crushes a PNG already encoded in a Base64 String." | |
method_options %w( clipboard -c ) => :boolean | |
def crush_64string(string = "") | |
if options.clipboard? | |
string = Clipboard.paste | |
puts "Getting string from clipboard" | |
else | |
string = string | |
end | |
#Setup temporary png path, decode the Base64 string, save the file. | |
temp_path = '/tmp/crush.png' | |
temp_png = File.open(temp_path, 'w+') {|f| f.write(Base64.decode64(string)) } | |
#Crush the temp file | |
crushed = PNGUtils.crush(temp_path) | |
#Encode crushed file to base64, copy to clipboard. | |
string = PNGUtils.encode(crushed) | |
Clipboard.copy string | |
#Delete the file created in by the crusher. | |
FileUtils.remove_file(crushed) | |
FileUtils.remove_file(temp_path) | |
#Display the all clear - In Green Text! | |
puts "\e[1m\e[32mBase64 String is in your Clipboard!\e[0m" | |
end | |
end | |
Pngto64.start #Required for thor executable. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment