出于学习目的,我正在使用Python + Flask创建一个站点。我想从数据库中恢复图像并在屏幕上显示。但是一步一步。
我不知道如何首先在我的数据库中保存图像。我的搜索只显示我必须在我的数据库中使用bytea
类型。然后我得到了我的图像,并以某种方式(??)将其转换为字节数组(bytea ==数组的咬合?)并以某种方式(??)在插入命令中使用此数组。
我能够发现(也许)如何在Java(here)和C#(here)中完成它,但我真的很想使用Python,至少目前是这样。
有人可以帮助我吗?
本网站有很多此类问题。但大多数(很容易超过85%)的回复都是“您不应该在数据库中保存图像,它们属于fs”并且无法回答问题。其余的并没有完全解决我的问题。因此,如果副本有这样的答案,请不要将其标记为重复。
答案 0 :(得分:25)
我通常不会为人们编写完整的示例程序,但是你没有要求它,这是一个非常简单的程序,所以你走了:
#!/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's large object support代替bytea
- 特别是lo_import
用于商店,lo_export
用于直接写入文件,以及大对象读取功能,用于一次读取图像的小块。
答案 1 :(得分:4)
我希望这对你有用。
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.
答案 2 :(得分:3)
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()
答案 3 :(得分: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中。
答案 4 :(得分:0)
您可以使用Python的base64将任意二进制字符串编码和解码为文本字符串。