Created
May 22, 2012 14:24
-
-
Save bspaulding/2769388 to your computer and use it in GitHub Desktop.
Convert and RGBA color on a specified background to an opaque RGB color.
This file contains 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 | |
# Pseudo Code | |
# - http://stackoverflow.com/questions/2049230/convert-rgba-color-to-rgb | |
# | |
# Source => Target = (BGColor + Source) = | |
# Target.R = ((1 - Source.A) * Source.R) + (Source.A * BGColor.R) | |
# Target.G = ((1 - Source.A) * Source.G) + (Source.A * BGColor.G) | |
# Target.B = ((1 - Source.A) * Source.B) + (Source.A * BGColor.B) | |
# rgba(150,150,150,0.4) | |
# rgb(63,45,108) | |
USAGE = <<-USAGE | |
rgba_to_rgb "Source.R,Source.G,Source.B" ["BG.R,BG.G,BG.B" || 255,255,255] | |
USAGE | |
class Color | |
attr_accessor :r, :g, :b, :a | |
def initialize(r,g,b,a = nil) | |
@r = r.to_f | |
@g = g.to_f | |
@b = b.to_f | |
@a = (a || 1).to_f | |
end | |
def flatten_alpha(bg_color = nil) | |
bg_color ||= Color.new(255,255,255,1) | |
target = Color.new(0,0,0) | |
target.r = ((1 - a) * r) + (a * bg_color.r) | |
target.g = ((1 - a) * g) + (a * bg_color.g) | |
target.b = ((1 - a) * b) + (a * bg_color.b) | |
target | |
end | |
def to_s | |
if a == 1.0 | |
"rgb(#{r}, #{g}, #{b})" | |
else | |
"rgba(#{r}, #{g}, #{b}, #{a})" | |
end | |
end | |
end | |
if ARGV[0].nil? | |
puts USAGE; exit(1) | |
end | |
if ARGV[1].nil? | |
ARGV[1] = "255,255,255" | |
end | |
source = Color.new(*ARGV[0].split(',')) | |
bg_color = Color.new(*(ARGV[1].split(','))) | |
target = source.flatten_alpha(bg_color) | |
puts " Source: #{source}" | |
puts "BGColor: #{bg_color}" | |
puts " Target: #{target}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment