Small Tool for color value conversion using Python, python color

Source: Internet
Author: User

Small Tool for color value conversion using Python, python color

First, let's take a look at the color value display example of Zeplin.

Original Processing Method

Because I will use Python (only input python on the terminal and use it as a calculator orhex()The function converts decimal to hexadecimal), so I certainly use python to solve this problem.hex() Convert the function and manually enter the result to Android Studio.


Use the hex function to manually convert the color value

Motivation

People are always too lazy to write this tool for a long time. I have also thought about it:

Input: decimal value similar to RGB (110,122 138), separated by space or comma.

Output: A hexadecimal RGB color value (# 6e7a8a ).

But I have never been able to do it, and I have been paying attention to it. Really lazy!

Start dry

1. First, I need to enter the Function

I opened the folder where I learned Python. There is exactly an example of raw_input:

#! /Usr/bin/python # coding = utf-8raw_input ("\ n input ")

Run on the terminalpython input.py You can enter text.

I need to receive user input information. How can I receive the message "forgot"? Google: Get the result. By the way, modify the input prompt and print the input content:

Input = raw_input ("\ n input color, for example, 50 144 60: \ n") print (input)

2. characters to be separated

Python character segmentation function found split()By default, blank spaces can be used to separate parameters. Originally, the English comma (,) is used as the separator. Now it seems that it can be saved and separated directly by space, no matter how many spaces can be automatically separated. Then add the Code:

rgbColorArray = input.split()print(rgbColorArray)

3. the array needs to be traversed.

I forgot how to retrieve the array in a simple way. I also searched:

for x in rgbColorArray: print(x)

4. Convert the character to hexadecimal

At this time, the string will be converted into a hexadecimal string. At this time, two functions are required,int() Andhex()The int function can convert a string to the int type, while hex accepts numeric parameters and returns a string. A string starting with 0x.

So we have the first version.

First version

Execution result of the first version

Writing such a basic version can basically get the result I want. The disadvantage is that I still need to manually earn the result and use the brain to remember the hexadecimal color value and then input it. You can copy the final result directly.

Further

Although the results have come out, I still hope to make some progress. There are several problems:

1. When the number to be converted is smaller than 16, only one digit is not displayed. For example, the result of 11 is 0xB.

2. The actual result is 0x more.

3. It is best to connect the displayed results to facilitate copying, rather than one line of each color.

Then we need to traverse the color value array, remove the 0x string, and add 0 to the front of the judgment smaller than 16. Output results consecutively.

For Loop traversal Array

Previously Usedfor Loop is an example from the query, but I don't know how to get it through multiple rows. Java writes are usually enclosed in braces.

Continue to query the information, so we know the following usage.

#! /Usr/bin/python #-*-coding: UTF-8-*-for num in range (): # iterations of numbers between 10 and 20 for I in range (2, num): # iteration Based on the factor if num % I = 0: # determine the first factor j = num/I # Calculate the second factor print '% d equals % d * % d' % (num, I, j) break # Jump out of the current loop else: # print num of the loop else, 'is a prime number'

Variable Declaration

Because we do not need line breaks, we need character connections instead of directprint.

Another problem occurs when declaring variables. Based on the usage of the preceding variables, I found some python code to check whether I need to declare any types. I just need to use them directly.

So with the code:

output = "#"for x in rgbColorArray:  intx = int(x) output = output + hex(intx)print(output)

Crop and splice strings.

Remove the extra 0x two digits.

Use string pruning to find examples.

#! /Usr/bin/pythonvar1 = 'Hello World! 'Var2 = "Python Runoob" print "var1 [0]:", var1 [0] print "var2 []:", var2 [] execution result of this example: var1 [0]: Hvar2 [1: 5]: ytho

By the way, I also asked my colleagues who are learning python. He told me that the index can be omitted, which means that the index can be cropped to the end.

For example, if print "var2[1:]", var2[1:] The result should beython Runoob

So there is code:

output = "#"for x in rgbColorArray:  intx = int(x) output = output + hex(intx)[2:]print(output)

It can also be written from the back to the front, for example, the above example. For example, ifprint "var2[-1:]", var2[-1:] The result should be ob, that is, the last two digits of the string.

So here we can writehex(intx)[-2:] (Because the output string is similar to 0x23, this is the case.) I wrote a bug later. I also explained what this bug is.

If else judgment

Next, let's make a judgment and add 0 to the first digit.

 if intx < 16:  output = output + '0' + hex(intx)[-2:] else:  output = output + hex(intx)[-2:]

In this way, the python file is available:

#! /Usr/bin/python # coding = utf-8input = raw_input ("\ n input color such as 50 144 60: \ n") # print (input) rgbColorArray = input. split () print (rgbColorArray) output = "#" for x in rgbColorArray: intx = int (x) if intx <16: output = output + '0' + hex (intx) [-2:] else: output = output + hex (intx) [-2:] # print (hex (int (x) print (output)

The last step is to add ColorU to the environment variable.

At this time, I can remember what I want, but it is a little inconvenient. I need to write it in the directory where the python file is located.

python colorU.py

Or write allcolorU.py This path. It is very troublesome, so I needcolorU Add it to the environment variable. I used zsh, so I found the environment variable configuration file :~ /. Zshrc. Add the following configuration at the end:

alias colorU="python ~/Documents/Development/PythonStudy/colorU.py"

This is the final feasible version after being guided by other colleagues. My initial thought wascolorU.py Set the file to an executable file and add it to the Path. As a resultcolorU.py The file address is added to the Path. The PATH in the world should be a directory. This makes it easier to add aliases.

Follow-up

Later, it was said that the Zeplin client could display the hexadecimal color value by default, but I used a webpage version, so no. That is to say, if I install the client, I don't need to write this script. But it doesn't matter if I learned python and wrote my first truly useful python code.

A bug: I found this bug only when I was writing this article. I wrote [-2:] When cropping strings like 0x33 from the back. Of course there is no problem, however, writing strings such as 0xf may cause problems. Input 5 5 5. The result is #0x50x50x5. Change to [2.


A bug caused by backward cropping strings

You can continue to upgrade your experience:

A. EntercolorU 231 234 123 You can get the result # e7ea7b;

B. In combination with Alfred, after calling out the Alfred window, enter the color value and get the result. Press enter to copy the hexadecimal format to the clipboard.

C. Save the previously converted color values to make it easier to reuse the color and copy the hexadecimal color directly.

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.