Random Color Generator with Hexadecimal Output

  • Share this:

Code introduction


This function generates a random color and returns it as a hexadecimal string. It first creates a white image, then generates a random RGB color and sets it as the color of the first pixel in the image. Finally, it converts the color to a hexadecimal string.


Technology Stack : Pillow, Image, ImageColor, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color():
    from random import randint
    from PIL import Image, ImageColor

    # Create a new white image
    img = Image.new('RGB', (100, 100), 'white')
    
    # Generate a random color
    random_color = (randint(0, 255), randint(0, 255), randint(0, 255))
    
    # Set the color of the image to the random color
    img.putpixel((0, 0), random_color)
    
    # Convert the image to a hex string
    hex_color = ImageColor.getrgb(random_color)
    hex_color_str = '#' + ''.join(f'{hex(c)[2:]:02x}' for c in hex_color)
    
    return hex_color_str