Save a image file on a Postgres database - Python
Last Updated :
28 Apr, 2025
In this article, we are going to see how to save image files on a postgresql database using Python.
Psycopg2 is a driver, that is used, for interacting, with Postgres data, using the Python scripting language. It is, used to perform, CRUD operations on Postgres data.
Data handled in applications can be in any format. For example, Strings, Numbers, and so on. At times, we need to upload, Images to the tables. In this article, let us learn, uploading images, to Postgres with Python.
BLOB and BYTEA format
Usually, Image fields, are BLOB data types. BLOBs are Binary Large Objects, which are, used to store, enormous amounts of data. Images, audio, and video files are usually stored, as BLOBs in databases. SQL, MySQL, and other databases, support BLOB datatype. But, Postgres does not supports, the BLOB format. Instead, it has a BYTEA format, for handling binary data. BYTEA is not suited, for storing, large amounts of data. A data column, of datatype BYTEA, can store up to, 1Gb of data.
Let us see, the steps involved, in uploading images, to the Postgres table -
- Let us consider, a database CartoonDB, having a table 'Cartoon'. It has fields cartoonID, name, cartoonImg. The field cartoon will be an INTEGER, the name will be TEXT, and, cartoonImg will be of BYTEA datatype.
- To perform CRUD operations, on Postgres data, using Python code, we need the psycopg2 library. Hence, install it, using the command - 'pip install psycopg2' at the terminal.
- The psycopg2 adapter, has 'connect()' method, that allows connection, to the database, by passing username, password, hostname, and port as parameters. We can pass the Database Name as well. It returns a valid connection object, on a successful connection.
- Using the connection object, we can create a cursor object, that acts as a pointer, to the database. We can use, the cursor object, to fire SQL queries, on the table data. Using it, we will Create, and, upload Image records, in the table.
The code for the same is as mentioned below -
Python3
# Import the required library
import psycopg2
# Method to create a connection object
# It creates a pointer cursor to the database
# and returns it along with Connection object
def create_connection():
# Connect to the database
# using the psycopg2 adapter.
# Pass your database name ,# username , password ,
# hostname and port number
conn = psycopg2.connect(dbname='DisneyDB',
user='postgres',
password='admin',
host='localhost',
port='5432')
# Get the cursor object from the connection object
curr = conn.cursor()
return conn, curr
def create_table():
try:
# Get the cursor object from the connection object
conn, curr = create_connection()
try:
# Fire the CREATE query
curr.execute("CREATE TABLE IF NOT EXISTS \
cartoon(cartoonID INTEGER, name TEXT,\
cartoonImg BYTEA)")
except(Exception, psycopg2.Error) as error:
# Print exception
print("Error while creating cartoon table", error)
finally:
# Close the connection object
conn.commit()
conn.close()
finally:
# Since we do not have to do anything here we will pass
pass
def write_blob(cartoonID,file_path,name):
try:
# Read data from a image file
drawing = open(file_path, 'rb').read()
# Read database configuration
conn, cursor = create_connection()
try:
# Execute the INSERT statement
# Convert the image data to Binary
cursor.execute("INSERT INTO cartoon\
(cartoonID,name,cartoonImg) " +
"VALUES(%s,%s,%s)",
(cartoonID,name, psycopg2.Binary(drawing)))
# Commit the changes to the database
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print("Error while inserting data in cartoon table", error)
finally:
# Close the connection object
conn.close()
finally:
# Since we do not have to do
# anything here we will pass
pass
# Call the create table method
create_table()
# Prepare sample data, of images, from local drive
write_blob(1,"F:\\TeachPytho\\GFGPhotos\\casper.jpg","Casper")
write_blob(2,"F:\\TeachPytho\\GFGPhotos\\archie.jpg","Archie")
write_blob(3,"F:\\TeachPytho\\GFGPhotos\\tintin.png","Tintin")
write_blob(4,"F:\\TeachPytho\\GFGPhotos\\pikachu.jpg","Pikachu")
write_blob(5,"F:\\TeachPytho\\GFGPhotos\\kungfupanda.jpg","Kung Fu Panda")
After executing the code, we can view the data in PgAdmin4 tool. The table data is as shown below -
Similar Reads
Python | Database management in PostgreSQL PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Py
6 min read
Saving a Plot as an Image in Python Sometimes we want to save charts and graphs as images or even images as a file on disk for use in presentations to present reports. And in some cases, we need to prevent the plot and images for future use. In this article, we'll see a way to save a plot as an image by converting it to an image, and
6 min read
Storing a BLOB in a PostgreSQL Database using Python This article focuses on, Storing BLOB in a PostgreSQL database. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To Store Blob data in a Postgres database Table, we will use psycopg2.The table for storing BLOB data in PostgreSQL is called a Large Object table and th
3 min read
CRUD Operations on Postgres using Async Database In Python CRUD stands for Create, Read, Update and Delete Operations. All these Operations can be made Asynchronous using the Async Database Connection. After making  Async Connection to Postgres Database, the performance of the Application improves significantly as all the operations are performed Concurrent
3 min read
How to use PostgreSQL Database in Django? This article revolves around how can you change your default Django SQLite-server to PostgreSQL. PostgreSQL and SQLite are the most widely used RDBMS relational database management systems. They are both open-source and free. There are some major differences that you should be consider when you are
2 min read
PostgreSQL - Connect To PostgreSQL Database Server in Python The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python s
4 min read
Making a Flask app using a PostgreSQL database The Postgres database can be accessed via one of two methods in Python. Installing PgAdmin4 is the first step because it offers a user interface for interacting with databases and another for using the psycopg2 connector. In this post, we'll concentrate on a different approach that lets us alter the
4 min read
Python | OpenCV program to read and save an Image OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. This is cross-platform library, it provides functions that are used in multiple languages. Coming to image processing, OpenCV enables us to perform multiple operations on image, but
2 min read
Handling PostgreSQL BLOB data in Python In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB)
5 min read
Python PIL save file with datetime as name In this article, we are going to see how to save image files with datetime as a name using PIL Python. Modules required: PIL: This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. pip install Pillow datetime: Thi
2 min read