Image based Steganography using Python
Last Updated :
04 Apr, 2025
Steganography (Hiding Data Inside Images) is the technique of concealing secret information within an image, audio, or video file. The goal is to embed data in such a way that it remains undetectable to the naked eye.
The idea behind image-based Steganography is very simple. Images are made up of pixels, and each pixel consists of three color values: Red, Green, and Blue (RGB). We can modify these values slightly to encode hidden data without significantly altering the image's appearance.
Encode Data into an Image:
1. Convert Data to Binary: Each character in the secret message is converted to its 8-bit binary representation using ASCII values.
2. Modify Pixel Values:
- Pixels are processed three at a time (9 RGB values in total).
- The first 8 values store binary data:
- If the binary bit is 1: make the value odd.
- If the binary bit is 0: make the value even.
- The 9th value ensures the message continues—it's even if there’s more data to encode.
For example :
Message to hide: "Hii" (3 bytes - needs 9 pixel values).
- H - ASCII 72 = Binary 01001000
- i - ASCII 105 = Binary 01101001
- i - ASCII 105 = Binary 01101001
- Total binary data = 24 bits
- Modify pixel values accordingly:
Original Pixels:
[(27, 64, 164), (248, 244, 194), (174, 246, 250),
(149, 95, 232), (188, 156, 169), (71, 167, 127),
(132, 173, 97), (113, 69, 206), (255, 29, 213),
(53, 153, 220), (246, 225, 229), (142, 82, 175)]
Take the first 3 pixels:
(27, 64, 164), (248, 244, 194), (174, 246, 250)
Convert 'H' (ASCII 72) to binary: 01001000
Modify pixel values:
0: Keep Even, 1: Make Odd
Original Value | Binary Bit | Modified Value |
---|
27 (Odd) | 0 → Make Even | 26 |
---|
64 (Even) | 1 → Make Odd | 63 |
---|
164 (Even) | 0 → Keep Even | 164 |
---|
248 (Even) | 0 → Keep Even | 248 |
---|
244 (Even) | 1 → Make Odd | 243 |
---|
194 (Even) | 0 → Keep Even | 194 |
---|
174 (Even) | 0 → Keep Even | 174 |
---|
246 (Even) | 0 → Keep Even | 246 |
---|
Final Modified Image (After Encoding "Hii"):
[(26, 63, 164), (248, 243, 194), (174, 246, 250), (148, 95, 231),
(188, 155, 168), (70, 167, 126), (132, 173, 97), (112, 69, 206),
(254, 29, 213), (53, 153, 220), (246, 225, 229), (142, 82, 175)]
Decode the data:
To extract the hidden message:
1. Read the image three pixels at a time.
2. Extract the binary values using the same encoding rule:
- Odd value - 1
- Even value - 0
3. Stop when the last value is odd, indicating the message has ended.
4. Convert the extracted binary sequence back to text.

Below is the Implementation of the above idea:
Python
from PIL import Image
def genData(data):
"""Converts input text into a list of 8-bit binary strings."""
return [format(ord(i), '08b') for i in data]
def modPix(pix, data):
"""Modifies pixel values to encode the binary data."""
datalist = genData(data)
lendata = len(datalist)
imdata = iter(pix)
for i in range(lendata):
pixels = [value for value in next(imdata)[:3] + next(imdata)[:3] + next(imdata)[:3]]
# Modify pixel values based on binary data
for j in range(8):
if datalist[i][j] == '0' and pixels[j] % 2 != 0:
pixels[j] -= 1
elif datalist[i][j] == '1' and pixels[j] % 2 == 0:
pixels[j] = pixels[j] - 1 if pixels[j] != 0 else pixels[j] + 1
# Set termination flag (last pixel even means continue, odd means stop)
if i == lendata - 1:
pixels[-1] |= 1 # Make odd (stop flag)
else:
pixels[-1] &= ~1 # Make even (continue flag)
yield tuple(pixels[:3])
yield tuple(pixels[3:6])
yield tuple(pixels[6:9])
def encode_enc(newimg, data):
"""Encodes the modified pixel data into the new image."""
w = newimg.size[0]
(x, y) = (0, 0)
for pixel in modPix(newimg.getdata(), data):
newimg.putpixel((x, y), pixel)
x = 0 if x == w - 1 else x + 1
y += 1 if x == 0 else 0
def encode():
"""Handles user input and calls encoding functions."""
img = input("Enter image name (with extension): ")
image = Image.open(img, 'r')
data = input("Enter data to be encoded: ")
if not data:
raise ValueError("Data is empty")
newimg = image.copy()
encode_enc(newimg, data)
new_img_name = input("Enter the name of new image (with extension): ")
newimg.save(new_img_name, new_img_name.split(".")[-1].upper())
def decode():
"""Decodes hidden text from an image."""
img = input("Enter image name (with extension): ")
image = Image.open(img, 'r')
imgdata = iter(image.getdata())
data = ""
while True:
pixels = [value for value in next(imgdata)[:3] + next(imgdata)[:3] + next(imgdata)[:3]]
binstr = ''.join(['1' if i % 2 else '0' for i in pixels[:8]])
data += chr(int(binstr, 2))
if pixels[-1] % 2 != 0:
break
return data
def main():
"""Main function for user interaction."""
choice = input(":: Welcome to Steganography ::\n1. Encode\n2. Decode\n")
if choice == '1':
encode()
elif choice == '2':
print("Decoded Word: " + decode())
else:
print("Invalid choice, exiting.")
if __name__ == "__main__":
main()
Output :
Terminal SnapshotSteps to Encode and Decode a Message
Encoding Steps (Hiding the Message)
- Run the script.
- Select 1 (Encode) when prompted.
- Enter the image filename (e.g., steganography-input.png).
- Enter the message, for example: This is a secret message from GFG
- Provide the output image name (e.g., encoded_image.png).
- The modified image is saved with hidden text.
Decoding Steps (Retrieving the Message)
- Run the script.
- Select 2 (Decode) when prompted.
- Enter the encoded image filename (e.g., encoded_image.png).
- The hidden message is displayed: This is a secret message from GFG
- That's it! Let me know if you need further clarification.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read