How To Hide Data in Images Using Python

The secret data can be data of any format like text or even a file. In a nutshell, the main motive of steganography is to hide the intended information within any file, usually an image, audio, or video, without actually changing the external appearance of the file, i.e. it should look the same as before.

In this blog, we will be focussing on learning image-based steganography, i.e. hiding secret data in an image.

But before diving a little deeper into it, let’s look at what an image comprises of.

  1. Pixels are the building blocks of an image.
  2. Every pixel contains three values: (red, green, blue) also known as RGB values.
  3. Every RGB value ranges from 0 to 255.

This much information is enough to get started.

Now, let’s look at how we can encode and decode data into our image.


There are a lot of algorithms that can be used to encode data into the image, and in fact, you can also make one yourself. The one being used in this blog is easy to understand and implement, as well.

The algorithm is as follows:

  1. For each character in the data, its ASCII value is taken and converted into 8-bit binary [1].
  2. Three pixels are read at a time having a total of 3*3=9 RGB values. The first eight RGB values are used to store one character that is converted into an 8-bit binary.
  3. The corresponding RGB value and binary data are compared. If the binary digit is 1 then the RGB value is converted to odd and, otherwise, even.
  4. The ninth value determines if more pixels should be read or not. If there is more data to be read, i.e. encoded or decoded, then the ninth pixel changes to even. Otherwise, if we want to stop reading pixels further, then make it odd.

Repeat this process until all the data is encoded into the image.


Suppose the message to be hidden is ‘Hii’.

The message is of three bytes, therefore, the pixels required to encode the data are 3 x 3 = 9. Consider a 4 x 3 image with a total of 12 pixels, which are sufficient to encode the given data.

[(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)]

Step 1

The ASCII value of H is 72, whose binary equivalent is 01001000.

Step 2

Read the first three pixels.

(27, 64, 164), (248, 244, 194), (174, 246, 250)

Step 3

Now, change the pixel value to odd for 1 and even for 0 as in the binary equivalent of data.

For example, the first binary digit is 0 and the first RGB value is 27, it needs to be converted to odd, which implies 26.

Similarly, 64gets converted to 63because the next binary digit is 1so the RGB value should be made odd.

So, the modified pixels are:

(26, 63, 164), (248, 243, 194), (174, 246, 250)

Step 4

Since we have to encode more data, the last value should be even. Similarly, i can be encoded in this image.

While making the pixel values odd/even by doing +1 or -1, you should take care of binary conditions. I.e., the pixel value should be more than or equal to 0 and less than or equal to 255.

The new image will look like:

[(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)]


For decoding, we shall try to find how to reverse the previous algorithm that we used to encode data.

  1. Again, three pixels are read at a time. The first 8 RGB values give us information about the secret data, and the ninth value tells us whether to move forward or not.
  2. For the first eight values, if the value is odd, then the binary bit is 1, otherwise it is 0.
  3. The bits are concatenated to a string, and with every three pixels, we get a byte of secret data, which means one character.
  4. Now, if the ninth value is even then we keep reading pixels three at a time, or otherwise, we stop.

For example

Let’s start reading three pixels at a time.

Consider our previously encoded image.

[(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)]

Step 1

We first read the three pixels:

[(26, 63, 164), (248, 243, 194), (174, 246, 250)

Step 2

Reading the first value: 26, which is even, therefore the binary bit is 0. Similarly, for 63, the binary bit is 1and for 164it is 0. This process continues until the eight RGB value.

Step 3

We finally get the binary value: 01001000 after concatenating all individual binary values. The final binary data corresponds to decimal value 72, and in ASCII, it represents the character H.

Step 4

Since the ninth value is even, we repeat the above steps. We stop when the ninth value encountered is odd.

As a result, we get our original message back which was Hii.

The Python program for the above algorithm is as follows:

# Python program implementing Image Steganography 

# PIL module is used to extract 
# pixels of image and modify it 
from PIL import Image 

# Convert encoding data into 8-bit binary 
# form using ASCII value of characters 
def genData(data): 
		# list of binary codes 
		# of given data 
		newd = [] 
		for i in data: 
			newd.append(format(ord(i), '08b')) 
		return newd 
# Pixels are modified according to the 
# 8-bit binary data and finally returned 
def modPix(pix, data): 
	datalist = genData(data) 
	lendata = len(datalist) 
	imdata = iter(pix) 

	for i in range(lendata): 
		# Extracting 3 pixels at a time 
		pix = [value for value in imdata.__next__()[:3] +
								imdata.__next__()[:3] +
		# Pixel value should be made 
		# odd for 1 and even for 0 
		for j in range(0, 8): 
			if (datalist[i][j]=='0') and (pix[j]% 2 != 0): 
				if (pix[j]% 2 != 0): 
					pix[j] -= 1
			elif (datalist[i][j] == '1') and (pix[j] % 2 == 0): 
				pix[j] -= 1
		# Eigh^th pixel of every set tells 
		# whether to stop ot read further. 
		# 0 means keep reading; 1 means the 
		# message is over. 
		if (i == lendata - 1): 
			if (pix[-1] % 2 == 0): 
				pix[-1] -= 1
			if (pix[-1] % 2 != 0): 
				pix[-1] -= 1

		pix = tuple(pix) 
		yield pix[0:3] 
		yield pix[3:6] 
		yield pix[6:9] 

def encode_enc(newimg, data): 
	w = newimg.size[0] 
	(x, y) = (0, 0) 
	for pixel in modPix(newimg.getdata(), data): 
		# Putting modified pixels in the new image 
		newimg.putpixel((x, y), pixel) 
		if (x == w - 1): 
			x = 0
			y += 1
			x += 1
# Encode data into image 
def encode(): 
	img = input("Enter image name(with extension): ") 
	image =, 'r') 
	data = input("Enter data to be encoded : ") 
	if (len(data) == 0): 
		raise ValueError('Data is empty') 
	newimg = image.copy() 
	encode_enc(newimg, data) 
	new_img_name = input("Enter the name of new image(with extension): "), str(new_img_name.split(".")[1].upper())) 

# Decode the data in the image 
def decode(): 
	img = input("Enter image name(with extension) :") 
	image =, 'r') 
	data = '' 
	imgdata = iter(image.getdata()) 
	while (True): 
		pixels = [value for value in imgdata.__next__()[:3] +
								imgdata.__next__()[:3] +
		# string of binary data 
		binstr = '' 
		for i in pixels[:8]: 
			if (i % 2 == 0): 
				binstr += '0'
				binstr += '1'
		data += chr(int(binstr, 2)) 
		if (pixels[-1] % 2 != 0): 
			return data 
# Main Function		 
def main(): 
	a = int(input(":: Welcome to Steganography ::\n"
						"1. Encode\n 2. Decode\n")) 
	if (a == 1): 
	elif (a == 2): 
		print("Decoded word- " + decode()) 
		raise Exception("Enter correct input") 
# Driver Code 
if __name__ == '__main__' : 
	# Calling main function 

The module used in the program is PILwhich stands for Python Imaging Library. It gives us the capability to perform operations on images in Python.

Program Execution

This is image title

This is image title

Input image

This is image title

Output image

This is image title


This program might not work as expected with JPEGimages because JPEG uses lossy compression which means that the pixels are modified to compress the image and reduce the quality, therefore data loss happens.

#python #programming

What is GEEK

Buddha Community

How To Hide Data in Images Using Python

george udosen


“27, it needs to be converted to odd, which implies 26”, this should be ‘even’ I believe but nice tutorial!

Ray  Patel

Ray Patel


top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Siphiwe  Nair

Siphiwe Nair


Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

Arvel  Parker

Arvel Parker


Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object







Built-in data types in Python

a**=str(“Hello python world”)****#str**














Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger




Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).


The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.


output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Ray  Patel

Ray Patel


Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Gerhard  Brink

Gerhard Brink


Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.


As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).

This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management