Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have an application which needs to save a database field type blob as a .gif or .jpg file format.

How may I do it?

Thanks.

Replies are listed 'Best First'.
Re: blob field
by mortis (Pilgrim) on Aug 12, 2004 at 02:49 UTC
    Many DBD drivers support BLOB columns natively. Most drivers/databases require you to use bind variables (which are usualy safer and often more efficient than composing quoted strings of sql code). Using bind params is not that difficult, assuming you are using mysql, and have a table named foo 'create table foo (data BLOB)', the following contrived example code should work for you:
    use strict; use warnings; use DBI; my $dbh = DBI->connect('dbi:mysql:krb','mortis',''); die $DBI::errstr unless $dbh; if (@ARGV) { my $img_file = 'test.jpg'; my $img_data = getFile($img_file); my $sql = 'INSERT INTO foo (data) VALUES (?)'; unless ($dbh->do($sql,undef,$img_data)) { die "Error executing sql: '$sql' : $DBI::errstr : ",$dbh->errstr," +\n"; } print "DATA INSERTED\n"; } my $resultSet = $dbh->selectall_arrayref('SELECT * FROM foo'); my $imgData = $resultSet->[0]->[0]; writeFile('test2.jpg',$imgData); $dbh->disconnect; sub getFile { my($file) = @_; my $fh; unless (open $fh, "<", $file) { die "Error opening $file : $!\n"; } my $data; { local $/ = undef; $data = <$fh>; } close $fh; return $data; } sub writeFile { my($file,$data) = @_; my $fh; unless (open $fh, ">", $file) { die "Error opening $file : $!\n"; } print $fh $data; close $fh; }

    Iirc, DBD::Oracle supports blobs natively in the same manner (you might have to pass statement handle attributes to identify the column's type though). DBD::Pg also supports blob columns, though you need to have blob access inside of a transaction, and you used to have to call some Postgresql specific DBD api to use them. Newer versions may be better.

    hth,

    Kyle

Re: blob field
by amt (Monk) on Aug 11, 2004 at 20:16 UTC
    Depending on the database implementation, storing binary data like images doesn't work well. I would suggest storing a URI for that image, and using your script to do the heavy work of fetching that file. amt.

      I've had good luck storing images in a PostgreSQL database using the bytea data type. Take a look at the bind_param section of DBD::Pg for more details on how to do it.

      As a handy trick for pulling the images back out and displaying them without knowing the file extension, use File::MMagic to figure out the what kind of image it is. I used this to specify the header type on a CGI application that retrieved stored images.

      However, if you're going to be storing a lot of images or speed is a concern, you're probably better off following amt's advice.