Heute ist dein Glückstag :)
Bild in Datenbank einfügen:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
use strict;
use warnings;
use Tk;
use Tk::PNG;
use Tk::JPEG;
use DBI;
my $datenbank = "test";
my $db_host = "localhost";
my $db_port = "3306";
my $db_user = "test";
my $db_pw = "test";
my $dsn = "DBI:mysql:database=$datenbank;host=$db_host;port=$db_port";
my $dbh = DBI->connect( $dsn, $db_user, $db_pw, { RaiseError => 1, PrintError => 0, AutoCommit => 1 } ) or die('Err connect: ' . DBI->errstr());
my $mw = Tk::MainWindow->new();
my $filename = "apply.png";
my $bild = $mw->Photo( -file => $filename );
open MYFILE, $filename or die "Cannot open file: $!";
binmode MYFILE;
my $data;
while (<MYFILE>) {
$data .= $_;
}
close MYFILE;
my $sql = q~INSERT INTO photos (photo) values (?)~;
my $sth = $dbh->prepare($sql) or die('Error prep: ' . $dbh->errstr());
$sth->bind_param(1, $data);
my $rv = $sth->execute($data) or die('Error exec: ' . $dbh->errstr());
my $label = $mw->Label(-image => $bild, -background => '#ffffff')->pack();
$mw->MainLoop();
Bild aus Datenbank auslesen und in Tk anzeigen:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use strict;
use warnings;
use DBI;
use Tk;
use Tk::PNG;
use Tk::JPEG;
use MIME::Base64 qw(encode_base64);
my $dbname = 'test';
my $username = 'test';
my $password = 'test';
my $dbh = DBI->connect("dbi:mysql:database=$dbname", $username, $password) or die "Cannot open db";
my $sql = "SELECT photo FROM photos LIMIT 1";
my $sth = $dbh->prepare($sql) or die('Error prep: ' . $dbh->errstr());
my $numrows = $sth->execute() or die('Error exec: ' . $dbh->errstr());
my $ref = $sth->fetchrow_hashref;
my $newdata = $$ref{'photo'};
$newdata = encode_base64($newdata);
my $mw = Tk::MainWindow->new();
my $bild = $mw->Photo( -data => $newdata );
my $label = $mw->Label(-image => $bild, -background => '#ffffff')->pack();
$mw->MainLoop();
Beim Einlesen ist wohl speziell bei Windows binmode() wichtig. Laut perldoc -f binmode sollte man das aber sowieso jedes Mal verwenden, wenn man Bilder in eine Variable einliest.
Und bei der Verwendung im Tk-Programm muss das Bild base64-kodiert sein. Das ist wohl eine Einschränkung (Feature?) von Tk. Wenn du die Bilder noch wo anders verwenden möchtest, dann speichere sie am besten richtig ab und kodiere sie in der Anwendung.
Achte auf die Größenbeschränkung der BLOB-Felder. Für mein 65,7 KB-großes Bild musste die Spalte schon als MEDIUMBLOB deklarieren.
Grüße,
pktm
Last edited: 2011-11-03 22:11:40 +0100 (CET)