🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 使用 Perl 在 SQLite 中处理图像 > 原文: [http://zetcode.com/db/sqliteperltutoriimg/](http://zetcode.com/db/sqliteperltutoriimg/) 在 SQLite Perl 教程的这一章中,我们将使用图像文件。 请注意,有些人反对将图像放入数据库。 在这里,我们只展示如何做。 我们不讨论是否在数据库中保存图像。 ```perl sqlite> CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB); ``` 对于此示例,我们创建一个名为`Images`的新表。 对于图像,我们使用`BLOB`数据类型,代表二进制大对象。 ## 插入图像 在第一个示例中,我们将图像插入 SQLite 数据库。 ```perl #!/usr/bin/perl use strict; use DBI; my $dbh = DBI->connect( "dbi:SQLite:dbname=test.db", { RaiseError => 1 } ) or die $DBI::errstr; open IMAGE, "mushrooms.jpg" or die $!; my ($image, $buff); while(read IMAGE, $buff, 1024) { $image .= $buff; } my $stm = $dbh->prepare("INSERT INTO Images(Data) VALUES (?)"); $stm->bind_param(1, $image, DBI::SQL_BLOB); $stm->execute(); close(IMAGE); $stm->finish(); $dbh->disconnect(); ``` 我们从当前工作目录中读取图像,并将其写入 SQLite `test.db`数据库的`Images`表中。 ```perl open IMAGE, "mushrooms.jpg" or die $!; ``` 我们打开一个图像。 这是称为`mushrooms.jpg`的 JPG 图像。 ```perl my ($image, $buff); while(read IMAGE, $buff, 1024) { $image .= $buff; } ``` 我们从图像文件读取二进制数据。 ```perl my $sth = $dbh->prepare("INSERT INTO Images(Data) VALUES (?)"); $sth->bind_param(1, $image, DBI::SQL_BLOB); $sth->execute(); ``` 三行代码准备 SQL 语句,将图像数据绑定到该语句并执行它。 ```perl close(IMAGE); $sth->finish(); $dbh->disconnect(); ``` 最后,我们正在释放资源。 ## 读取图像 在本节中,我们将执行相反的操作。 我们将从数据库表中读取图像。 ```perl #!/usr/bin/perl use strict; use DBI; my $dbh = DBI->connect( "dbi:SQLite:dbname=test.db", { RaiseError => 1 } ) or die $DBI::errstr; my $stm = $dbh->prepare("SELECT Data FROM Images WHERE Id=1"); $stm->execute(); my $image = $stm->fetch(); print "Image: $image"; open IMAGE, ">mushrooms2.jpg" or die $!; print IMAGE @$image; close(IMAGE); $stm->finish(); $dbh->disconnect(); ``` 我们从`IMAGE`表中读取图像数据,并将其写入另一个文件,我们称为蘑菇`2.jpg`。 ```perl my $sth = $dbh->prepare("SELECT Data FROM Images WHERE Id=1"); $sth->execute(); my $image = $sth->fetch(); ``` 这三行从表中选择图像数据。 ```perl open IMAGE, ">mushrooms2.jpg" or die $!; print IMAGE @$image; close(IMAGE); ``` 我们打开一个新的图像文件,并将检索到的数据写入该文件。 然后我们关闭文件。 SQLite Perl 教程的这一部分专门用于读取和写入图像。