Random Color Generator to Hexadecimal String

  • Share this:

Code introduction


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