Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an image in postgresql database

I would like to know How can I insert an image "bytea" into a table of my postgreSql database? I've been searching forums for hours and have seen the same question posted dozens of times, but yet to find a single answer. All I see is how to insert .jpeg's into an old column which isn't what I need.

Here's the database table:

create table category  (
"id_category" SERIAL,
"category_name" TEXT,
"category_image" bytea,
constraint id_cat_pkey primary key ("id_category"))without oids;

and when I add a new line, it doesn't work :

insert into category(category_name,category_image) values('tablette', lo_import('D:\image.jpg'));
like image 626
Sarra Avatar asked Mar 09 '14 22:03

Sarra


People also ask

How do I insert an image into a Postgres table?

To insert an image, you would use: File file = new File("myimage. gif"); FileInputStream fis = new FileInputStream(file); PreparedStatement ps = conn. prepareStatement("INSERT INTO images VALUES (?, ?)"); ps.

Can we store images in PostgreSQL database?

use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc. use a separate database with DBlink: for original image store, at another (unified/specialized) database.

What is the data type for image in PostgreSQL?

With the BLOB data type, you can store the content of a picture, a document, etc. into the table. PostgreSQL does not support BLOB but you can use the BYTEA data type for storing the binary data.

Can I store image in database?

To insert images into a database, the database must support images. Images are stored in binary in a table cell. The data type for the cell is a binary large object (BLOB), which is a new SQL type in SQL3 for storing binary data.


3 Answers

insert into category(category_name,category_image) values('tablette', bytea('D:\image.jpg'));

The above solution works if column type is bytea

insert into category(category_name,category_image) values('tablette', lo_import('D:\image.jpg'));

The above solution works if column type is oid i.e., Blob

insert into category(category_name,category_image) values('tablette',decode('HexStringOfImage',hex));

The above decode function take two parameters. First parameter is HexString of Image.The second parameter is hex by default.Decode function coverts the hexString to bytes and store in bytea datatype column in postgres.

like image 179
Ravi Avatar answered Sep 19 '22 12:09

Ravi


None of the above example worked well for me and on top of that I needed to add many images at once.

Full working example (python 3) with explanations:

With get_binary_array we get the value of the image (or file) as a binary array, using its path and file name as parameter (ex: '/home/Pictures/blue.png').

With send_files_to_postgresql we send all the images at once.

I previously created the database with one sequential 'id' that will automatically be incremented (but you can use your own homemade id) and one bytea 'image' field

import psycopg2

def get_binary_array(path):
    with open(path, "rb") as image:
        f = image.read()
        b = bytes(f).hex()
        return b

def send_files_to_postgresql(connection, cursor, file_names):
    query = "INSERT INTO table(image) VALUES (decode(%s, 'hex'))"
    mylist = []
    for file_name in file_names:
        mylist.append(get_binary_array(file_name))

    try:
        cursor.executemany(query, mylist)
       
        connection.commit()  # commit the changes to the database is advised for big files, see documentation
        count = cursor.rowcount # check that the images were all successfully added
        print (count, "Records inserted successfully into table")
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

def get_connection_cursor_tuple():
    connection = None
    try:
        params = config()
        print('Connecting to the PostgreSQL database...')
        connection = psycopg2.connect(**params)
        cursor = connection.cursor()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

    return connection, cursor

connection, cursor = connect_db.get_connection_cursor_tuple()
img_names = ['./blue.png', './landscape.jpg']
send_files_to_postgresql(connection, cursor, img_names)
like image 28
Antonin GAVREL Avatar answered Sep 19 '22 12:09

Antonin GAVREL


If the column type is bytea then you can simply use the 'pg_read_binary_file'.

Example: pg_read_binary_file('/path-to-image/')

check postgresql documentation of pg_read_binary_file

like image 35
Mowazzem Hosen Avatar answered Sep 18 '22 12:09

Mowazzem Hosen