Python プログラムを使用して画像を MySQL に保存する方法

WBOY
リリース: 2023-04-19 15:16:08
転載
1328 人が閲覧しました

環境

Python 3.7.4
pymysql
8.0.11 MySQL Community Server
ログイン後にコピー

画像の読み取り

画像をバイナリ形式で読み取る

with open("./test.jpg", "rb") as file:
	image = file.read()
ログイン後にコピー

画像を保存するテーブルの作成

画像フィールドの属性は次のとおりです。 longblog、つまり long バイナリ ラージ オブジェクト

def create_image_table(self):
	sql = 'create table if not exists picture ( \
        image longblob);'

    try:
        self.cursor.execute(sql)

        self.connection.commit()

    except pymysql.Error:
        print(pymysql.Error)
ログイン後にコピー

は MySQL に格納されます

画像データをバイナリ形式で MySQL

def insert_image(self, image):
    sql = "insert into picture(image) values(%s)"
    self.cursor.execute(sql, image)
    self.connection.commit()
ログイン後にコピー
に格納します

MySQLクエリで取得した画像データをpictureとして保存

画像をバイナリ形式で記述する

def get_image(self, path):
    sql = 'select * from picture'
    try:
        self.cursor.execute(sql)
        image = self.cursor.fetchone()[0]
        with open(path, "wb") as file:
            file.write(image)
    except pymysql.Error:
        print(pymysql.Error)
    except IOError:
        print(IOError)
ログイン後にコピー

実装コード

import pymysql


class Database():
	
	'''
		Description:
			database demo to store image in MySQL RDBMS
		Attributes:
			None
	'''
    
    def __init__(self):
        self.connection = pymysql.connect(host=&#39;<host name>&#39;,user=&#39;<user name>&#39;,passwd=&#39;<password>&#39;,db=&#39;<database name>&#39;,charset=&#39;utf8&#39;)
        self.cursor = self.connection.cursor()

	&#39;&#39;&#39;
		Description:
			create table to store images
		Args:
			None
		Return:
			None
	&#39;&#39;&#39;
    
    def create_image_table(self):
        sql = &#39;create table if not exists picture ( \
            image longblob);&#39;

        try:
            self.cursor.execute(sql)

            self.connection.commit()

        except pymysql.Error:
            print(pymysql.Error)
	
	&#39;&#39;&#39;
		Description:
			insert image into table
		Args:
			image:
				image to store
		Returns:
			None
	&#39;&#39;&#39;

    def insert_image(self, image):
        sql = "insert into picture(image) values(%s)"
        self.cursor.execute(sql, image)
        self.connection.commit()
	
	&#39;&#39;&#39;
		Description:
			get image from database
		Args:
			path:
				path to save image
		Returns:
			None
	&#39;&#39;&#39;	

    def get_image(self, path):
        sql = &#39;select * from picture&#39;
        try:
            self.cursor.execute(sql)
            image = self.cursor.fetchone()[0]
            with open(path, "wb") as file:
                file.write(image)
        except pymysql.Error:
            print(pymysql.Error)
        except IOError:
            print(IOError)
            
	&#39;&#39;&#39;
		Description:
			destruction method
		Args:
			None
		Returns:
			None
	&#39;&#39;&#39;
	
    def __del__(self):
        self.connection.close()
        self.cursor.close()

if __name__ == "__main__":
    database = Database()
    # read image from current directory
    with open("./test.jpg", "rb") as file:
        image = file.read()

    database.create_image_table()
    database.insert_image(image)

    database.get_image(&#39;./result.jpg&#39;)
ログイン後にコピー

テスト結果

Python プログラムを使用して画像を MySQL に保存する方法#

以上がPython プログラムを使用して画像を MySQL に保存する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:yisu.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!