I have a script that generates a random hex code, and from that, I would like to generate an image with the generated color as the fill of the image. I looked at pylab, but was unable to get the result I was looking for. Could someone please assist me in figuring out how to do this?
2 Answers
The Python Image Library (PIL, the maintained fork is called Pillow) can be used to create an image file.
from PIL import Image
webhexcolor = "#4878A8"
im = Image.new("RGB", (100,100), webhexcolor)
im.save( "color.png")
-
-
Providing an image library that allows OP to solve their problem counts as assistance in my view, but I have added code.– handleJun 23, 2016 at 18:28
Upvote if you find this useful:
#Hex to RGB
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3))
print(hex_to_rgb("#0022ff"))
#https://www.codespeedy.com/create-random-hex-color-code-in-python/
import random
import cv2
def generate_random_hex():
random_number = random.randint(0,16777215)
hex_number = str(hex(random_number))
hex_number ='#'+ hex_number[2:]
print('A Random Hex Color Code is :',hex_number)
return hex_number
width1, height1 = 300, 300
random_hex_code=generate_random_hex()
random_rgb_code=hex_to_rgb(random_hex_code)
image = create_blank(width1, height1, rgb_color=random_rgb_code)
cv2.imwrite('random'+random_hex_code+'.jpg', image)
-
This is a bit late, but for generating the hex code if you're using this solution, you can also use
random.getrandbits(24)
Aug 23, 2022 at 0:11