CSS color extracter

This is one of the reasons I love Ruby. I wrote some code that would take a CSS file and print out the unique hex colors, and it was about 10 lines long. I then realized that if I had been thinking in Ruby, I could do it in just one line.

This page is OLD and probably contains errors, out of date information, security flaws or other problems. I am keeping it around because it might be helpful to someone.

File.readlines(ARGV[0]).to_s.downcase.scan(/#[0-9a-f]{6}/).uniq.sort.each {|one| puts one} if (ARGV[0] != nil)

Put that in a Ruby file, and run it with a parameter of the CSS file to parse, and it will print each unique color on a single line.

Expanding on that work, we can now create Gimp palettes for use in a variety of Open Source graphics programs, including Inkscape and The Gimp. Here is a program that will do just that.
Download it here

#!/usr/bin/env ruby
# Create a gimp palette from a CSS file's unique hex colors
# Weakenesses: Doesn't account for 3 digit colors (ie. #abc;)
# or for named colors
# By Michael Moore stuporglue@gmail.com
# Released to Public Domain April 5, 2007
if (ARGV[0] != nil)
    gimpstring = "GIMP Palette\nName: "
    if(ARGV[1] != nil)
	gimpstring << ARGV[1]
	gimpstring << ARGV[0]
    gimpstring << "\nColumns: 0\n#"
    # This could have problems if you have ids that are only hex chars for the first 6 values
    # eg. if this were your CSS
    #	#abc123nurserystyle {
    # 		background-color: green;
    #	}
    #	the color #abc123 would be added to the palette

    File.readlines(ARGV[0]).to_s.downcase.scan(/#[0-9a-f]{6}/).uniq.sort.each do |onecolor|
	colorparts = onecolor.scan(/[0-9a-f]{2}/)
	gimpstring << "\n" + colorparts[0].hex.to_s.rjust(3) + " " + colorparts[1].hex.to_s.rjust(3) + " " + colorparts[2].hex.to_s.rjust(3) + "\tUntitled"
    print gimpstring
    puts ""
    puts "CSS to Gimp Palette"
    puts "Use 6-digit hex colors from a CSS file to create a Gimp palette (gpl) file"
    puts ""
    puts "USAGE: csstogpl.rb cssfile [Palette Name]"
    puts "If Palette Name is ommited, the CSS file's name will be used instead"
    puts ""
    puts "Note: csstogpl does not write to a file, it prints to stdout."
    puts "To save to a file, use redirection. eg."
    puts "csstogpl.rb style.css MyAwesomeColorScheme > MACS.gpl"
    puts ""

This entry was posted in Programming, Projects and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *