15

出于学习目的,我正在使用 Python+Flask 创建一个站点。我想从数据库中恢复图像并将其显示在屏幕上。而是一步一个脚印。

我不知道如何将图像保存在我的数据库中。我的搜索只显示我必须bytea在我的数据库中使用一种类型。然后我得到我的图像并以某种方式(??)将其转换为字节数组(bytea == 咬数组?)并以某种方式(??)在插入命令中使用该数组。

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

有人能帮我吗?

这个网站上有很多这样的问题。但他们中的大多数(轻松超过 85%)被回答为“您不应该将图像保存在数据库中,它们属于 fs”并且无法回答问题。其余的并不能完全解决我的问题。因此,如果重复项有这种答案,请不要将其标记为重复项。

4

5 回答 5

30

我通常不会为人们编写完整的示例程序,但您并不需要它,而且它是一个非常简单的程序,所以您开始吧:

#!/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直接写入文件以及一次读取小块图像的大对象读取功能。

于 2013-05-27T00:11:49.590 回答
5

我希望这对你有用。

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 图像

于 2013-05-26T22:40:50.353 回答
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()
于 2014-10-07T09:48:38.803 回答
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中。

于 2016-03-06T04:40:46.513 回答
0

您可以使用 Python 的base64将任意二进制字符串编码和解码为文本字符串。

于 2013-05-26T21:50:26.603 回答