You can download this code by clicking the button below.
This code is now available for download.
This function generates a random color and returns it as a hexadecimal string.
Technology Stack : Pillow library (Image module and ImageColor module)
Code Type : Function
Code Difficulty : Intermediate
def random_color():
from random import randint
from PIL import Image, ImageColor
# Create a new white image
image = Image.new("RGB", (100, 100), "white")
# Generate a random color
random_color = (randint(0, 255), randint(0, 255), randint(0, 255))
# Draw a red rectangle on the image
draw = ImageDraw.Draw(image)
draw.rectangle([(10, 10), (90, 90)], fill=random_color)
# Convert the image to a hex string
hex_color = ImageColor.getrgb(random_color)
return hex_color