如何在Postgres数据库中保存图像文件?

15

为了学习目的,我正在使用Python+Flask创建一个网站。我想从数据库中恢复一张图片并在屏幕上显示它。但是要一步步来。

我根本不知道如何首先将图像保存在我的数据库中。我的搜索只显示我必须在我的数据库中使用bytea类型。然后我获取我的图像并以某种方式(??)将其转换为字节数组(bytea ==位数组?),并以某种方式(??)在插入命令中使用此数组。

我能够在Java(这里)和C#(这里)中发现(也许)如何做到这一点,但我真的很想使用Python,至少现在是这样。

有人能帮我吗?

这个网站上有很多这种问题。但大多数(超过85%)的回复都是“您不应该将图像保存在数据库中,它们属于文件系统”,并且没有回答问题。其余的则无法完全解决我的问题。因此,如果重复的问题具有此类答案,请不要将其标记为重复。


除了bytea之外,还有使用“大对象”的选项。这里是一个带有手册链接的选项列表。虽然没有Python特定的解决方案。 - Erwin Brandstetter
好的,不涉及Python。那么一般来说,我需要对图像做什么?获取文件并将其转换为字符串?获取字符串并将其变成二进制?我不明白的是,在您的fs中的“image.jpg”和它的bytea数据之间发生了什么。 - Felipe Matos
5个回答

31

我通常不会为别人编写完整的示例程序,但您没有要求,而且这是一个非常简单的示例,所以请看以下代码:

#!/usr/bin/env python3

import os
import sys
import psycopg2
import argparse

db_conn_str = "dbname=regress user=craig"

create_table_stm = """
CREATE TABLE files (
    id serial primary key,
    orig_filename text not null,
    file_data bytea not null
)
"""

def main(argv):
    parser = argparse.ArgumentParser()
    parser_action = parser.add_mutually_exclusive_group(required=True)
    parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB")
    parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42')
    parser.add_argument("filename", help="Name of file to write to / fetch from")

    args = parser.parse_args(argv[1:])

    conn = psycopg2.connect(db_conn_str)
    curs = conn.cursor()

    # Ensure DB structure is present
    curs.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = %s AND table_name = %s", ('public','files'))
    result = curs.fetchall()
    if len(result) == 0:
        curs.execute(create_table_stm)

    # and run the command
    if args.store:
        # Reads the whole file into memory. If you want to avoid that,
        # use large object storage instead of bytea; see the psycopg2
        # and postgresql documentation.
        f = open(args.filename,'rb')

        # The following code works as-is in Python 3.
        #
        # In Python 2, you can't just pass a 'str' directly, as psycopg2
        # will think it's an encoded text string, not raw bytes. You must
        # either use psycopg2.Binary to wrap it, or load the data into a
        # "bytearray" object.
        #
        # so either:
        #
        #   filedata = psycopg2.Binary( f.read() )
        #
        # or
        #
        #   filedata = buffer( f.read() )
        #
        filedata = f.read()
        curs.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (args.filename, filedata))
        returned_id = curs.fetchone()[0]
        f.close()
        conn.commit()
        print("Stored {0} into DB record {1}".format(args.filename, returned_id))

    elif args.fetch is not None:
        # Fetches the file from the DB into memory then writes it out.
        # Same as for store, to avoid that use a large object.
        f = open(args.filename,'wb')
        curs.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(args.fetch),))
        (file_data, orig_filename) = curs.fetchone()

            # In Python 3 this code works as-is.
            # In Python 2, you must get the str from the returned buffer object.
        f.write(file_data)
        f.close()
        print("Fetched {0} into file {1}; original filename was {2}".format(args.fetch, args.filename, orig_filename))

    conn.close()

if __name__ == '__main__':
    main(sys.argv)

本文使用Python 3.3编写。如果要使用Python 2.7,需要读取文件并将其转换为buffer对象或使用大型对象函数。转换为Python 2.6及更早版本需要安装argparse,可能需要进行其他更改。

如果您要测试运行,请将数据库连接字符串更改为适合您系统的内容。

如果您正在处理大型图像,请考虑使用psycopg2的大型对象支持,而不是bytea - 特别是使用lo_import进行存储,使用lo_export直接写入文件,以及使用大型对象读取函数每次读取小块图像。


太好了!这正是我在寻找的!我已经成功地按照之前的答案将文件插入到数据库中,但是当我尝试恢复它时仍然感到迷茫。由于我正在使用Python 2.7,所以我必须使用缓冲区对象,就像你说的那样,但它们看起来很难使用!我会进行一些研究。谢谢,这真的很有帮助! - Felipe Matos
@FelipeMatos 另外,请记住,虽然上面的示例将从数据库加载的图像保存到文件中,但您可以轻松地将其从缓冲区加载到PIL图像以供显示,发送到http客户端等。您很少需要将其写入磁盘 - 如果确实需要,通常会使用tempfile.TemporaryFile - Craig Ringer

5
我希望这对您有用。
请注意:保留HTML标记。
import Image
import StringIO
im = Image.open("file_name.jpg") # Getting the Image
fp = StringIO.StringIO()
im.save(fp,"JPEG")
output = fp.getvalue() # The output is 8-bit String.

StringIO Image


好的,我尝试了一下,差不多可以工作。供以后参考,我首先从这里安装了Python Image Library。我能够使用你的代码运行查询(这是一个很好的信号),但我的数据库是UFT-8,所以我发现有编码问题。经过一些关于编码的研究,我发现(惊喜!)psycopg支持这种操作,就在这里。我按照这些步骤成功插入了条目,现在我需要找出如何恢复它。 - Felipe Matos
1
没有必要在PIL中实际加载图像,您只需要读取文件并将其存储在数据库中。尽管如此,这是一个有用的示例,加一分。 - Craig Ringer
@CraigRinger 您是正确的。但如果将图像修改并存储为缩略图,我想这将会很有用。 :) - iraycd

4
import psycopg2
import sys

def readImage():
    try:
        fin = open("woman.jpg", "rb")
        img = fin.read()
        return img

    except IOError, e:
        print "Error %d: %s" % (e.args[0],e.args[1])
        sys.exit(1)

    finally:
        if fin:
            fin.close()
try:
    con = psycopg2.connect(database="testdb", user="abc")
    cur = con.cursor()
    data = readImage()
    binary = psycopg2.Binary(data)
    cur.execute("INSERT INTO images(id, data) VALUES (1, %s)", (binary,) )
    con.commit()
except psycopg2.DatabaseError, e:
    if con:
        con.rollback()
    print 'Error %s' % e    
    sys.exit(1)
finally: 
    if con:
        con.close()

当我尝试这样做时,出现了“*** TypeError:无法将实例转换为二进制”。 - reetesh11
将数据转换为 psycopg2.Binary 对我来说是关键,谢谢! - Matt

1

这是我的解决方案,在我的网站上可以工作:

@main.route('/upload', methods=['GET', 'POST'])
def upload_avatar():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            current_user.avatar_local = file.read()
            db.session.add(current_user)
            db.session.commit()
            return redirect(url_for('main.user_page', username=current_user.username))
    return render_template('upload_avatar.html', user=current_user)

使用Flask和Flask-Alchemy来处理数据库。
{% block edit_avatar  %}
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
{% endblock %}

这是一个HTML文件。你可以将它嵌入到你的HTML中。

0

你可以使用Python的base64对任意二进制字符串进行编码和解码,转换成文本字符串。


你可以这样做,但那不是正确的答案。数据库可以高效地存储二进制数据在bytea字段中,因此对其进行base64编码是完全没有必要的。 - Craig Ringer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接