473,383 Members | 1,918 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Re: tool to calculate color combination

Astan Chee skrev:
Hi,
I was just wondering if there is a tool/script in python that allows me
to do color calculations; specifically, when I add them.
There is the colorsys module which I have used in this class:


from colorsys import rgb_to_hls, hls_to_rgb
import binascii
from types import StringType, TupleType, ListType, IntType, FloatType
from math import modf

class RGB:
""" Makes it easier to work with rgb colors """

def __init__(self, color):
# set color value
self.color = self.any2color(color)

def any2color(self, color):
"""
Takes a number of color formats and returns a sequence of 3
floats:
(r,g,b)
Some legal formats for pure blue are:
'0x0000FF','#0000FF','0000FF',
[0.0, 0.0, 1.0], [0, 0, 255], (0, 0.0, 'FF') and ('0', '0', 'f').
Mixed types are allowed in sequences.
"""
# it must be a hex, so convert to sequence of hex values
if isinstance(color, StringType):
# handle hex value
if color[:2].lower() == '0x': color = color[2:]
elif color[0] == '#': color = color[1:]
color = (color[:2], color[2:4], color[4:])
# convert sequence to floats
color_result = []
a = color_result.append
for part in color:
# what type is the part?
if isinstance(part, StringType): # hex part
if len(part) == 1:
part = '0%s' % part
b = binascii.a2b_hex(part)
a(ord(b[0])/255.0)
elif isinstance(part, IntType): # int part
a(part/255.0)
elif isinstance(part, FloatType): # float part
a(part)
return color_result
def __str__(self):
"Returns string representation of color (same as html_hex)"
return self.html_hex()
def r(self):
return self.color[0]

def g(self):
return self.color[1]

def b(self):
return self.color[2]
def bytes(self):
"""
Takes a sequence of colors in floats, and returns a sequence of
int in
the range 0-255
"""
return map(lambda x: int(x*255), self.color)
def html_hex(self):
"""
Returns the color in a hex string representation of the form
'#0000FF'
"""
r,g,b = self.color
return '#%02X%02X%02X' % (int(r*255),int(g*255),int(b*255))
def _cAdd(self, x, y):
"Private method! Cirkular add x+y so value allways in 0.0-1.0
range"
fractional, integer = modf(x + y)
if not fractional and integer: # special case 1.0
return 1.0
return abs(fractional)
# wrong result for negative values!
def hls_delta(self, dh, dl, ds):
"""
Returns a Color object same as self, but adjusted by delta hls
values
"""
h,l,s = rgb_to_hls(*self.color)
nh = self._cAdd(h, dh)
nl = l + dl
if nl 1.0: nl = 1.0
if nl < 0.0: nl = 0.0
ns = s + ds
if ns 1.0: ns = 1.0
if ns < 0.0: ns = 0.0
return RGB(hls_to_rgb(nh, nl, ns))
def change_ls(self, new_l=None, new_s=None):
"""
Returns a Color object same as self, but with new lightness and
saturation levels
"""
h,l,s = rgb_to_hls(*self.color)
if new_l == None:
new_l = l
if new_s == None:
new_s = s
return RGB(hls_to_rgb(h, new_l, new_s))
def spacer(self, transparent=None):
"""
Creates a 1x1 GIF89a of color. If no color it returns a
transparent gif
Should probably not be in this module?
"""
template = [71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 0, 0, 255,
255,
255, 0, 0, 0, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0,
1, 0,
0, 2, 2, 68, 1, 0, 59]
if not transparent:
template[13:16] = self.bytes() # set rgb values
template[22] = 0 # remove transparency
return ''.join(map(chr, template))

if __name__=='__main__':

red = (255, 0, 0)
green = (0.0, 1.0, 0.0)
blue = (0.0, 0.0, 1.0)
yellow = '#ffff00'

col = RGB(blue)
print col.color
print col.bytes()
print col

brighter = col.change_ls(0.0, 0.0)
print 'brighter:',brighter

# complementary = col.hls_delta(0.50, 0.0, 0.0)
# print complementary
--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Jun 27 '08 #1
0 1184

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: petermichaux | last post by:
Hi, I've been playing with php5 with Smarty templates and mySQL4 and PEAR DB for e-commerce. This combination seems to work very well but I was wondering what other other combination of...
4
by: Mark Light | last post by:
Hi, I have a tk.scale bar for which I want the background to change from blue to red as I slide along it. The mechanics of this I can do, but the colour gradient I have is very crude - basically...
7
by: Randy | last post by:
Hi Folks, I've recently completed a new information management and help authoring tool; it's available as a free download on my web site. I call it Foundation. It's written in VB.NET, and...
9
by: Sandy | last post by:
Hello - I need either a cheap tool or code & DB that calculates, eg. within 50-mile radius of a zip code. Anyone have any suggestions? -- Sandy
1
by: Tom | last post by:
Hi folks, I'm looking for something to make from my c# project code an scheme with connections between functions. It would be than easy to find redundand functions. An very very very example:...
16
by: kazak | last post by:
Hello, I am looking for C code analysing tool, My problem is: To discover the portion of code that depends on(deals with) a number of specified structures and variables. Sample: void...
0
by: fiona | last post by:
FOR IMMEDIATE RELEASE Catalyst release low cost logic processing tool 87% of defects in software are errors in logic Yucca Valley, CA, September 2006 - Catalyst Development Corporation,...
13
by: Angus | last post by:
Hello I have a stream of bytes - unsigned char*. But the 'string' may contain embedded nulls. So not like a traditional c string terminated with a null. I need to calculate the length of...
0
by: Astan Chee | last post by:
Hi, I was just wondering if there is a tool/script in python that allows me to do color calculations; specifically, when I add them. Also I was thinking that for this to work other than a simple...
0
by: Astan Chee | last post by:
Dont worry about this. I've figured it out. Rather simple : red = sum of for each red (50/100) * 1 green = sum of for each green (50/100) * 0 blue = sum of for each blue(50/100) * 0 Astan Chee...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.