Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to use PostgreSQL Database in Django?
Next article icon

Save a image file on a Postgres database – Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 –

 



Next Article
How to use PostgreSQL Database in Django?

P

phadnispradnya
Improve
Article Tags :
  • Python
Practice Tags :
  • python

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
    5 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 Concurrentl
    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
  • Insert Python list into PostgreSQL database
    In this article, we will discuss how to Insert a Python list into PostgreSQL database using pyscopg2 module. Psycopg2 is the most popular PostgreSQL adapter for the Python programming language. Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-
    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
  • Create a database in MongoDB using Python
    MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditiona
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences