For learning purposes, I'm creating a site using Python+Flask. I want to recover an image from database and show it on screen. But one step at a time.
I have no idea how to save an image in my database in the first place. My searches only revealed that I have to use a bytea
type in my database. Then I get my image and somehow (??) convert it to an array of bytes (bytea == array of bites?) and somehow (??) use this array in a insert command.
I was able to discover (maybe) how to do it in Java (here) and C# (here), but I would really like to use Python, at least for now.
Can someone help me?
There are tons of questions of this kind in this site. But most (easily over 85%) of them are replied as "You shouldn't save images in your database, they belong in fs" and fail to answer the question. The rest don't quite solve my problem. So please don't mark this as duplicate if the duplicate has this kind of answer.
You can use Python's base64 for encoding and decoding arbitrary binary strings into text strings.
I hope this will work for you.
StringIO Image
that's my solution, it can work in my website:
using Flask,Flask-Alchemy to handle database.
that's html file.you can embed it in you html.
I don't normally write complete example programs for people, but you didn't demand it and it's a pretty simple one, so here you go:
Written with Python 3.3. Using Python 2.7 requires that you read the file and convert to a
buffer
object or use the large object functions. Converting to Python 2.6 and older requires installation of argparse, probably other changes.You'll want to change the database connection string to something suitable for your system if you're going to test-run it.
If you're working with big images consider using psycopg2's large object support instead of
bytea
- in particular,lo_import
for store,lo_export
for writing directly to a file, and the large object read functions for reading small chunks of the image at a time.