1

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?

1
  • What stops you from generating an rgb color instead.
    – Bálint
    Jun 23, 2016 at 18:10

2 Answers 2

4

The Python Image Library (PIL, the maintained fork is called Pillow) can be used to create an image file.

Following https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#example-draw-a-gray-cross-over-an-image

from PIL import Image
webhexcolor = "#4878A8"
im = Image.new("RGB", (100,100), webhexcolor)
im.save( "color.png")
2
  • this seems like more of a comment, not an answer.
    – Lexi
    Jun 23, 2016 at 18:17
  • Providing an image library that allows OP to solve their problem counts as assistance in my view, but I have added code.
    – handle
    Jun 23, 2016 at 18:28
0

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)
1
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.