How can i convert blob data received from database to image in python
You no need cv2 for convert blob to image, you need to store on disk the blob/image and show it. here and example of retrive from mysql blob to disk file..
import mysql.connector from mysql.connector import Error def write_file(data, filename): # Convert binary data to proper format and write it on Hard Disk with open(filename, 'wb') as file: file.write(data) def readBLOB(emp_id, photo, bioData): print("Reading BLOB data from python_employee table") try: connection = mysql.connector.connect(host='localhost', database='python_db', user='pynative', password='pynative@#29') cursor = connection.cursor() sql_fetch_blob_query = """SELECT photo from python_employee where cursor.execute(sql_fetch_blob_query, (emp_id,)) record = cursor.fetchall() for row in record: print("Id = ", row[0], ) print("Name = ", row[1]) image = row[2] file = row[3] print("Storing employee image and bio-data on disk \n") write_file(image, photo) write_file(file, bioData) except mysql.connector.Error as error: print("Failed to read BLOB data from MySQL table <>".format(error)) finally: if (connection.is_connected()): cursor.close() connection.close() print("MySQL connection is closed") readBLOB(1, "D:\Python\Articles\my_SQL\query_output\eric_photo.png", "D:\Python\Articles\my_SQL\query_output\eric_bioData.txt") readBLOB(2, "D:\Python\Articles\my_SQL\query_output\scott_photo.png", "D:\Python\Articles\my_SQL\query_output\scott_bioData.txt")
Danilo Mercado Oudalova 565
If you want to save the image, use the code from ‘Danilo Mercado Oudalova’.
But if you want to use without save file, use the example below.
import mysql.connector from mysql.connector import Error from io import BytesIO #from io import StringIO. import PIL.Image try: connection = mysql.connector.connect(host='localhost', database='python_db', user='pynative', password='pynative@#29') cursor = connection.cursor() sql = "your query" cursor.execute(sql) result = cursor.fetchall() except mysql.connector.Error as error: print("Failed to read BLOB data from MySQL table <>".format(error)) finally: if (connection.is_connected()): cursor.close() connection.close() print("MySQL connection is closed") type(result[0][0]) #If the type is byte, use from io import BytesIOf. If str, use from io import StringIO. file_like= BytesIO(result[0][0]) img=PIL.Image.open(file_like) img.show()
송준석 951
Related Query
- How can i convert blob data received from database to image in python
- How to create and update a SQL database with real-time data received from a python socket?
- How can I send data from a python script to Matplotlib?
- python how to read bytes type data from file and convert it to utf-8?
- How do I convert .asc data of CAN to .blf using python as per vector format
- How do I convert .blf data of CAN to .asc using python
- How to read an image file from ftp and convert it into an opencv image without saving in python
- How can I convert my python script to a package that is callable from the commandline?
- How can I download tick data from Bloomberg using the xbbg python library?
- How can I use Python to generate nested JSON data from my CSV file
- How can we convert JSON to .csv file using python ? my json value has array of data and dictionary formation as :
- How can I use python to combine data from multiple excel files into one excel file?
- In python 3, how can i transfer the data from a 2d array into a csv textfile
- How can I send data from a TCP Python server to a client and vice-versa?
- How can I convert a row from a dataframe in pyspark to a column but keep the column names? — pyspark or python
- Storing data received via MQTT from ESP32 in a Python Database
- How can I read data from AWS- Aurora postgresql as python pandas DataFrame and write the same to Oracle table?
- How can I change the data type of data that is being extracted from string to money or decimal in python
- How can I select the image link from src html part using python selenium
- How can I save my output image arrays into a specific folder on my computer from my python code in JupyterLab workbook?
- How to retrieve actual blob data rather than «oracle.sql.blob@» from an Oracle database over JDBC?
- How to write data from python database to excel spreadsheet?
- How can I render an image from a PDF with python as Microsoft Edge is doing?
- How can i compare data output from robot framework by using python
- how can i send some data from php to python
- Abaqus Python: How can I edit or remove data from an odb output database
- Python — How to convert a string from binary to integer list?
- How to pass data by ‘POST’ method to from Javascript to Python
- Reading binary data (image data type) from SQL database and inflate it, Matlab vs. Python
- How can i convert my python list to another list format
- how can i print return values (success/failure) from a python script
- How can I find additional files installed with my python package from an included script?
- How can I eliminate my custom __import__ hook from Python backtraces
- How can I convert SQLite 2 to SQLite3 using Python on Windows?
- How can we retrieve data from datastore?
- How to retrieve a time stamp with the right formatting from a sql database using python
- How to convert data and time to a number of days in python (pandas)
- how can I change the attribute value in supercalass from subclass permanently in python
- How can I quickly show python help documentation from emacs without opening a Python shell?
- How to pull Data into python from SAP ERP
- How do I convert a multiple paged PDF into a PNG image per pdf page in Python
- How can I change background color to red of an image using Python
- How do I convert a unicode text to a text that python can read so that I could find that specific word in webscraping results?
- how to add image in header and keep first page header and footer different from other pages using google docs API in python
- How I can convert for loop in python using map function
- How can I convert a list to JSON/dictionary — Python
- How to extract the data from encoded HTML class using python
- How to send the data from one computer to another device on the same WiFi network via python socket program?
- How to convert draw.io compressed data from exported png file to xml
- How to convert a python for loop from sequential to run parallel
More Query from same tag
- Is there a way to turn a rectangle into a circle in pygame?
- How to get a session in a custom defined metric?
- calculating sale price based on dependent fees in python
- Python — Manage cursor connection outside context manager
- How do i make this discord bot to send message to specific channel?
- Does requests.session expires if remained idle?
- Dependencies plot-vcfstats in conda environment
- Select Dictionary from list of Dictionaries and make some updates
- Does flask-admin import html templates on runtime?
- Scikit-Learn LinearReression Doesn’t preform well, on a very simple data set,
- Why doesn’t my if statement not work in while loop?
- Altair Line Plot with Two Lines and Log-Scaled Y-Axis
- Why do we have to append path for Rdkit in Google Colab
- How to pass bytes object in Python to a C++ function wrapped with Swig?
- Order Django Queryset by attribute that could be char or int?
- TypeError: fit() got an unexpected keyword argument ‘test’
- Python BeautifulSoup — extract text and attribute values
- Handling subsets of shared resources in Simpy
- Permission denied: ‘dbt_modules’
- Get task_id of failed task from within an Airflow DAG level failure callback
- How to restrict PyPi project search by adding search terms?
- Fixing «pyproj import _datadir» error: specified module could not be found
- How to add comman data in a list of
- Zip files in FTP using Python
- Trying to make it so function main() recognizes specific integers when calling upon function problem_solving
- Trying to use Python + XPath to click the highlighted text?
- Show chaco plot in running thread
- Good training accuracy but poor validation accuracy
- How to add comma in selenium python after every two line?
- Plot a RGB point on the imshow
- interacting with slurm jobs in python
- how to access source tree in Twisted trial tests?
- python — point system in a 2 player game
- Specifying a custom Fipy boundary condition of an «L» shaped geometry
- Python whois fails after converting to an exe
Чтение изображения из SQLite
9 октября 2015 г. Archy Просмотров: 14153 RSS Обсудить
SQLite » Общие вопросы create image python, image sqlite, python example, python примеры, изображение python
В этой статье, мы собираемся выполнять обратную операцию. Мы будем читать изображение из таблицы базы данных. В прошлой статье мы записали данные изображения в таблицу, теперь мы превратим эти данные обратно в изображение.
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 as lite import sys def writeImage(data): try: fout = open('woman2.jpg','wb') fout.write(data) except IOError, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) finally: if fout: fout.close() try: con = lite.connect('test.db') cur = con.cursor() cur.execute("SELECT Data FROM Images LIMIT 1") data = cur.fetchone()[0] writeImage(data) except lite.Error, e: print "Error %s:" % e.args[0] sys.exit(1) finally: if con: con.close()
Мы читаем данные изображения из таблицы Images и пишем их в другой файл, который мы называем woman2.jpg. В базу данных можно сохранять изображения для капч, используя небольшой список русских слов (как это делает Яндекс) и выводить их для пользователя. Можно скрипт капчи скачать и использовать уже готовый для своих проектах.
try: fout = open('woman2.jpg','wb') fout.write(data)
Мы открываем двоичный файл в режиме записи. Данные из базы данных записываются в файл.
cur.execute("SELECT Data FROM Images LIMIT 1") data = cur.fetchone()[0]
Эти две строки выбирают и получают данные из таблицы Images. Мы достаём двоичные данные из первой строки.