🎨 Lesson: Color Codes, Images, and Base64
🎯 Objective
By the end of this lesson, you will be able to:
- Understand RGB and Hex color codes.
- Describe how digital images are made of colored pixels.
- Understand and use Base64 encoding for images.
🌈 Understanding Color Representation
🟥 RGB Color Codes
RGB = Red, Green, Blue
Each component ranges from 0–255.
Examples:
# RGB examples
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
print("Red:", red)
print("Green:", green)
print("Blue:", blue)
🔢 Hexadecimal (Hex) Color Codes
Hex is the base-16 version of RGB:
- Red =
#FF0000
- Green =
#00FF00
- Blue =
#0000FF
Each pair of hex digits represents one RGB value (R, G, B).
🍿 Popcorn Hack #1
Use an online color picker (like Google or colorpicker.me).
Pick your favorite color and write down its RGB and Hex code.
🍿 Popcorn Hack #2
Challenge: Can you guess the hex code for purple?
Hint: It’s a mix of red and blue.
🧩 3. How Images Work
Digital images are made of pixels, each with a color value.
Let’s simulate a tiny image (3x3 pixels) using RGB values:
# Simulating a 3x3 pixel image using RGB values
image = [
[(255, 0, 0), (0, 255, 0), (0, 0, 255)],
[(255, 255, 0), (0, 255, 255), (255, 0, 255)],
[(128, 128, 128), (255, 255, 255), (0, 0, 0)]
]
for row in image:
print(row)
Each row is a line of pixels. Each color is stored using RGB values.
🔐 4. What is Base64 Encoding?
Base64 turns binary (image) data into text.
Used to:
- Embed images directly into HTML or emails
- Avoid separate file uploads
Let’s try it on a small image.
🛠️ Base64 Example
Convert an image to Base64 using Python:
import base64
# Read image as bytes
with open("example.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
# Print a short version
print(encoded_string[:100]) # first 100 characters of Base64 string
The result is a long string of letters, numbers, and symbols — a text version of the image!
🍿 5. Popcorn Hack #3
Decode a Base64 string and display it.
Try this sample:
import base64
# Sample Base64 string (represents the word "hello")
sample = "aGVsbG8="
decoded = base64.b64decode(sample)
print("Decoded string:", decoded.decode("utf-8"))
🍿 Popcorn Hack #4
- Go to a Base64 decoder like base64decode.org
- Paste in a longer string (from a converted image) and see what happens!
✅ Wrap-Up: What Did You Learn? Homework Hack #1
- What does
#00FF00
mean? - What is RGB?
- Why might someone use Base64 for an image?
📝 Homework Hack #2
Find the Hex code of your favorite color and explain what its RGB values are.
If you’d like, try converting a tiny image into Base64 and include it in a basic HTML page.