Images are text?!
YEAR 9 DIGITAL TECHNOLOGIES
DATA REPRESENTATION
PYTHON + FILES + BASE64
How can a computer show an image?
In this lesson, you will move from simple text pictures to image files, then into a much stranger question: What if you needed to keep everything in just one file?
LEARNING INTENTION
We are learning to...
understand different ways that images can be represented, stored, loaded, and displayed by a computer.
SUCCESS CRITERIA
By the end, you should be able to...
explain how file paths work, use Python to load an image, convert an image into base64 text, and use that text to display the image again.
CHALLENGE QUESTION
How would you show an image in a game or webpage?
Think about the simplest possible answer first.
Prompt 1: Where would the image file need to be stored?
Prompt 2: How would your Python program find it?
Prompt 3: What would happen if the image was moved into another folder?
1. Warm-up: images made from text (ASCII art)
What is the big idea here?
KEY IDEA
An image does not always need to be stored as an image file. Sometimes, text alone can create something your brain still recognises as a picture.
Think: If this is just text, why does your brain still see an image?
Simple ASCII example
/\_/\\
( o.o )
> ^ <
Richer ASCII example
/\ /\
/ \'.__ (\_/) __.\' \
/_.''.__'--('.')--'__.''._\
| \_ / `;=/ " \=;` \ _/ |
\/ `\__|`\___/`|__/` \/
\(/|\)/
_.-" ` "`-._
.' \___/ '.
/ (o o) \
| \_/ |
| \ / |
\ '. .' /
'. `'---'` .'
'-._____.-'
Try this
TRY THIS
Change one character only in the simple example. What changes in the “image”?
2. Project setup: where should the image files live?
Why does folder structure matter?
IMPORTANT
Python can only load a file if it knows where the file is. That means your folder structure and your filenames matter.
Use this folder structure
image_project/
│
├── main.py
├── digitech_banner.png
└── images/
└── pirate_chicken.png
main.py = your Python program
digitech_banner.png = image in the same folder as the Python file
images/pirate_chicken.png = image inside a subfolder called images
Path example: same folder
SAME FOLDER
To load the banner image, use:
digitech_banner.png
Path example: subfolder
SUBFOLDER
To load the pirate image, use:
images/pirate_chicken.png
Common mistakes
COMMON MISTAKES
Spelling matters. Capitals matter. File extensions matter. .png is not the same as .jpg. A missing folder name will also break the path.
3. First solution: open an image directly from Python
What is this approach doing?
IDEA
If the image file already exists on the computer, one simple option is to tell the operating system to open it.
This does not put the image inside your Python file. It just opens the existing file.
Worked example: image in the same folder
# ============================================================
# OPEN AN IMAGE FILE DIRECTLY
# ============================================================
# This program opens an image that already exists in the same
# folder as the Python file.
#
# IMPORTANT:
# • The image must already exist
# • The filename must be spelled exactly correctly
# ============================================================
import webbrowser # Used to open files using the default app
# This image is in the SAME folder as the Python file
image_file = "digitech_banner.png"
# Open the image using the operating system's default program
webbrowser.open(image_file)
print("If the path is correct, the image should now open.")
Worked example: image in a subfolder
# ============================================================
# OPEN AN IMAGE FROM A SUBFOLDER
# ============================================================
# This program opens an image stored inside a folder called
# "images".
#
# IMPORTANT:
# • The folder name must be correct
# • The filename must be correct
# • The slash is part of the file path
# ============================================================
import webbrowser # Used to open files using the default app
# This image is inside the "images" subfolder
image_file = "images/pirate_chicken.png"
# Open the image using the operating system's default program
webbrowser.open(image_file)
print("If the path is correct, the image should now open.")
4. Another solution: show an image in a temporary webpage
Why would we use a webpage?
WEB IDEA
A webpage can also display an image by pointing to its file path. This is closer to how websites often work.
Worked example: temporary webpage
# ============================================================
# SHOW AN IMAGE IN A TEMPORARY WEBPAGE
# ============================================================
# This program creates a simple HTML page and opens it in a
# browser. The image file must already exist.
#
# IMPORTANT:
# • The image path must be correct
# • This example uses an image from a subfolder
# ============================================================
import tempfile # Used to create a temporary HTML file
import webbrowser # Used to open the HTML file in the browser
# The image file we want the webpage to display
image_path = "images/pirate_chicken.png"
# Build a simple HTML page as a multi-line string
html = f"""
Pirate Chicken
"""
# Save the HTML into a temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=".html", mode="w") as f:
f.write(html)
path = f.name
# Open the temporary webpage in the browser
webbrowser.open(path)
print("If the image path is correct, it should appear in the browser.")
5. Constraint twist: what if you are only allowed one file?
The problem
PROBLEM
Your earlier solutions depended on the image existing as a separate file. But what if you had to submit just one file?
What stops working?
You can no longer rely on:
• an extra image file
• an images/ folder
• a normal file path
New direction
Could you turn the image into text and keep that text inside the program?
6. New idea: base64 turns image data into text
What is base64?
BASE64
Base64 is a way of representing binary data as text characters. That means an image can be converted into a long string of letters, numbers, and symbols.
Why does that matter?
WHY THIS MATTERS
If the image becomes text, you can keep that text inside a Python program or inside a webpage.
What does base64 look like?
/9j/4AAQSkZJRgABAQAAAQABAAD...lots more text here...
7. Task 1: convert an image into base64 text and save it
Task goal
TASK 1 GOAL
Take an existing image file, convert it into base64 text, save the text into a new file, and optionally open that text file to inspect it.
Task 1 code
# ============================================================
# TASK 1: IMAGE → BASE64 (SAVE + OPTIONAL VIEW)
# ============================================================
# This program will:
# 1. Take an image file (JPG or PNG)
# 2. Convert it into base64 (text version of the image)
# 3. Save that text into a .txt file
# 4. Give you the OPTION to open the text file
#
# ------------------------------------------------------------
# ⚠️ BEFORE YOU START:
# ------------------------------------------------------------
# • Your image MUST be in the SAME folder as this Python file
# • You MUST type the filename EXACTLY (including extension)
# • Example: digitech_banner.png
# ============================================================
import base64
import os
import webbrowser # Used to open the file if the user chooses
# ------------------------------------------------------------
# STEP 1: Get the image file name
# ------------------------------------------------------------
image_file = input("Enter the image file name (e.g. digitech_banner.png): ")
# Python will look for this file in the SAME folder as this script
# ------------------------------------------------------------
# STEP 2: Open the image in binary mode
# ------------------------------------------------------------
# "rb" = read binary (images are NOT text files)
try:
with open(image_file, "rb") as img:
image_data = img.read()
except FileNotFoundError:
print("❌ ERROR: File not found.")
print("Check that:")
print("• The image is in the SAME folder")
print("• The filename is correct (including .png or .jpg)")
exit()
# ------------------------------------------------------------
# STEP 3: Convert binary → base64
# ------------------------------------------------------------
encoded_data = base64.b64encode(image_data)
# ------------------------------------------------------------
# STEP 4: Convert bytes → string
# ------------------------------------------------------------
encoded_string = encoded_data.decode("utf-8")
# ------------------------------------------------------------
# STEP 5: Generate output file name
# ------------------------------------------------------------
# Example:
# digitech_banner.png → digitech_banner_base64.txt
name, extension = os.path.splitext(image_file)
output_file = f"{name}_base64.txt"
# ------------------------------------------------------------
# STEP 6: Save base64 string to file
# ------------------------------------------------------------
with open(output_file, "w") as f:
f.write(encoded_string)
# ------------------------------------------------------------
# STEP 7: Confirm success
# ------------------------------------------------------------
print(f"\\n✅ Base64 successfully saved to '{output_file}'")
# ------------------------------------------------------------
# STEP 8: Give user the OPTION to open the file
# ------------------------------------------------------------
choice = input("\\nDo you want to open the text file? (y/n): ").lower()
if choice == "y":
# This will open the file in the default program
webbrowser.open(output_file)
print("📄 Opening file...")
else:
print("👍 You can open it later if you want.")
Checkpoint
CHECKPOINT
Did your program create a new file ending in _base64.txt?
8. Task 2: paste base64 text into Python and display the image in a webpage
Task goal
TASK 2 GOAL
Copy the base64 text from your saved file, paste it into a Python program, and use it to rebuild the image inside a temporary webpage.
Task 2 code
# ============================================================
# TASK 2: BASE64 → IMAGE VIEWER (PASTE VERSION)
# ============================================================
# This program will:
# 1. Let you paste base64 data (text version of an image)
# 2. Ask what type of image it is
# 3. Display the image in a browser
#
# ------------------------------------------------------------
# ⚠️ BEFORE YOU START:
# ------------------------------------------------------------
# • Paste ONLY the base64 string (NOT "data:image/..." part)
# • Your string should look like: /9j/4AAQSkZJRgABAQAAAQABAAD...
# • Press ENTER twice when finished pasting
# ============================================================
import tempfile
import webbrowser
# ------------------------------------------------------------
# STEP 1: Paste base64 data
# ------------------------------------------------------------
print("Paste your base64 string below.")
print("Press ENTER twice when you are done.\\n")
lines = []
while True:
line = input()
# An empty line means the user has finished pasting
if line == "":
break
lines.append(line)
# Join all lines into one continuous string
base64_string = "".join(lines)
# ------------------------------------------------------------
# STEP 2: Ask for image type
# ------------------------------------------------------------
print("\\nWhat type of image is this?")
print("1. JPG / JPEG")
print("2. PNG")
choice = input("Enter 1 or 2: ")
if choice == "1":
mime_type = "image/jpeg"
elif choice == "2":
mime_type = "image/png"
else:
print("⚠️ Invalid choice — defaulting to JPEG")
mime_type = "image/jpeg"
# ------------------------------------------------------------
# STEP 3: Create HTML using pasted base64
# ------------------------------------------------------------
html = f"""
Decoded Image
"""
# ------------------------------------------------------------
# STEP 4: Save HTML + open in browser
# ------------------------------------------------------------
with tempfile.NamedTemporaryFile(delete=False, suffix=".html", mode="w") as f:
f.write(html)
path = f.name
webbrowser.open(path)
print("\\n🌐 Webpage opened!")
Checkpoint
CHECKPOINT
If your image does not appear, check the image type and make sure you pasted only the base64 text.
9. Discussion and reflection
Discuss
DISCUSS
What is the difference between loading an image by file path and embedding it as base64 text?
Reflect
REFLECT
Why might a programmer choose the simpler file-path method most of the time?
Submit
SUBMIT
Post a short response explaining how this lesson connects ASCII art, file paths, and base64.
Big idea
Computers do not “see” an image the way humans do. They work with representations: sometimes a file path, sometimes binary data, sometimes plain text.