473,569 Members | 2,490 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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','#00 00FF','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(colo r, 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.ap pend
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_he x(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*2 55))
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(*sel f.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(*sel f.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=Non e):
"""
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__=='__ma in__':

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:',bri ghter

# 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 1195

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

Similar topics

6
1333
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 programming tools would be good. JSP, ASP, C#? I don't know about those languages or how they compare to php. Any thoughts? Thanks, Peter
4
5172
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 the amount of R in RGB just increases whilst the G and B are fixed values. Whilst this is not really a python question does anybody have any...
7
1171
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 should be of interest to .NET developers who have a use for a documentation tool that can be tightly integrated with .NET applications to provide dynamic...
9
3435
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
1090
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: void Main(int t) {
16
1893
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 funct(struct header* h) {
0
1586
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, publisher of SocketWrench and SocketTools, today announced the release of its first application software, a logic processing software tool. LogicGem is...
13
3318
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 these arrays but can't use strlen because it just stops counting at the first null it finds. so how to do it? Angus
0
701
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 way, some form of measure is included. e.g 50% red(1,0,0) + 50% yellow(1,1,0) = 100% orange(1,0.7,0) Is there such a tool in python? Thanks for any...
0
202
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 wrote: -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two."
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7678
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7982
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6286
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3644
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.