跳转至

在 MySQL 中使用 Perl 处理图像

原文: http://zetcode.com/db/mysqlpeimg/

在 MySQL Perl 教程的这一章中,我们将使用图像文件。 请注意,有些人反对将图像放入数据库。 在这里,我们只展示如何做。 我们不讨论是否将图像保存在数据库中的技术问题。

mysql> CREATE TABLE Images(Id INT PRIMARY KEY, Data MEDIUMBLOB);

对于此示例,我们创建一个名为Images的新表。 对于图像,我们使用 MySQL MEDIUMBLOB数据类型,该数据类型存储二进制对象。

插入图像

在第一个示例中,我们将图像插入 MySQL 数据库。

#!/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表中。

open IMAGE, "woman.jpg" or die $!;

我们打开一个图像。 这是称为woman.jpg的 JPG 图像。

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();

三行代码准备 SQL 语句,将图像数据绑定到该语句并执行它。

close(IMAGE);
$sth->finish();
$dbh->disconnect();

最后,我们正在释放资源。

读取图像

在本节中,我们将执行相反的操作。 我们将从数据库表中读取图像。

#!/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中。

my $sth = $dbh->prepare("SELECT Data FROM Images WHERE Id=1");
$sth->execute();
my $image = $sth->fetch();

这三行从表中选择图像数据。

open IMAGE, ">woman2.jpg" or die $!;
print IMAGE @$image;
close(IMAGE);

我们打开一个新的图像文件,并将检索到的数据写入该文件。 然后我们关闭文件。

MySQL Perl 教程的这一部分专门用于读取和写入图像。


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组