💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 在 MySQL 中使用 Perl 处理图像 > 原文: [http://zetcode.com/db/mysqlpeimg/](http://zetcode.com/db/mysqlpeimg/) 在 MySQL Perl 教程的这一章中,我们将使用图像文件。 请注意,有些人反对将图像放入数据库。 在这里,我们只展示如何做。 我们不讨论是否将图像保存在数据库中的技术问题。 ```perl mysql> CREATE TABLE Images(Id INT PRIMARY KEY, Data MEDIUMBLOB); ``` 对于此示例,我们创建一个名为`Images`的新表。 对于图像,我们使用 MySQL `MEDIUMBLOB`数据类型,该数据类型存储二进制对象。 ## 插入图像 在第一个示例中,我们将图像插入 MySQL 数据库。 ```perl #!/usr/bin/perl use strict; use DBI; my $dbh = DBI->connect( "dbi:mysql:dbname=mydb", "user12", "34klq*", { RaiseError => 1 }, ) or die $DBI::errstr; open IMAGE, "woman.jpg" or die $!; my ($image, $buff); while(read IMAGE, $buff, 1024) { $image .= $buff; } my $stm = $dbh->prepare("INSERT INTO Images(Id, Data) VALUES (1, ?)"); $stm->bind_param(1, $image, DBI::SQL_BLOB); $stm->execute(); close(IMAGE); $stm->finish(); $dbh->disconnect(); ``` 我们从当前工作目录中读取图像,并将其写入 MySQL `mydb`数据库的`Images`表中。 ```perl open IMAGE, "woman.jpg" or die $!; ``` 我们打开一个图像。 这是称为`woman.jpg`的 JPG 图像。 ```perl my ($image, $buff); while(read IMAGE, $buff, 1024) { $image .= $buff; } ``` 我们从图像文件读取二进制数据。 ```perl my $stm = $dbh->prepare("INSERT INTO Images(Id, Data) VALUES (1, ?)"); $stm->bind_param(1, $image, DBI::SQL_BLOB); $stm->execute(); ``` 三行代码准备 SQL 语句,将图像数据绑定到该语句并执行它。 ```perl close(IMAGE); $sth->finish(); $dbh->disconnect(); ``` 最后,我们正在释放资源。 ## 读取图像 在本节中,我们将执行相反的操作。 我们将从数据库表中读取图像。 ```perl #!/usr/bin/perl use strict; use DBI; my $dbh = DBI->connect( "dbi:mysql:dbname=mydb", "user12", "34klq*", { RaiseError => 1 }, ) or die $DBI::errstr; my $stm = $dbh->prepare("SELECT Data FROM Images WHERE Id=1"); $stm->execute(); my $image = $stm->fetch(); open IMAGE, ">woman2.jpg" or die $!; print IMAGE @$image; close(IMAGE); $stm->finish(); $dbh->disconnect(); ``` 我们从`Images`表中读取图像数据,并将其写入另一个文件`woman2.jpg`中。 ```perl my $sth = $dbh->prepare("SELECT Data FROM Images WHERE Id=1"); $sth->execute(); my $image = $sth->fetch(); ``` 这三行从表中选择图像数据。 ```perl open IMAGE, ">woman2.jpg" or die $!; print IMAGE @$image; close(IMAGE); ``` 我们打开一个新的图像文件,并将检索到的数据写入该文件。 然后我们关闭文件。 MySQL Perl 教程的这一部分专门用于读取和写入图像。