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

I am trying to write a jpg to a sqlite database and read it back. The read-back info says that the file maybe corrupted. The original size is 120,453 and the read-back file is 120,895 consistently.
use strict; use warnings; use util_routines; use DBI; my $my_picture_file = "c:\\users\\xxx\\work\\blob.jpg"; my $dbname = "a.dat"; my $dbh = util_routines::connect_to_sqlite($dbname); create_my_blob(); open (my $MYFILE,'<', $my_picture_file) or die "Cannot open file....$ +!"; my $data; { local $/; $data = <$MYFILE>; close $MYFILE; } $data =~ s/^\s+//g; $data =~ s/\s+$//g; # insert image into table my $sql = "INSERT INTO my_blob VALUES (?)"; my $sth = $dbh->prepare($sql) or die; $sth->execute($data) or die; # retrieve image from table $sql = "SELECT image FROM my_blob"; $sth = $dbh->prepare($sql) or die; $sth->execute() or die; my $ref = $sth->fetchrow_hashref; my $newdata = $$ref{'image'}; $newdata =~ s/^\s+//g; $newdata =~ s/\s+$//g; open (my $OUTPUT, '>', "output_blob.jpg") or die "$!\n"; print $OUTPUT $newdata; close $OUTPUT; $sth->finish; $dbh->disconnect; sub create_my_blob { $dbh->do('drop table my_blob'); my $sql = qq/create table my_blob (image blob)/; $dbh->do($sql) or die "\n\n$DBI::errstr"; print "Created my_blob\n"; return; } __END__
OS os win7 with Strawberry Perl v5.24.1

Replies are listed 'Best First'.
Re: corruption of jpg written and retrieved from sqlite
by choroba (Cardinal) on May 15, 2017 at 15:30 UTC
    Quoting from binmode:

    > On some systems (in general, DOS- and Windows-based systems) binmode is necessary when you're not working with a text file.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: corruption of jpg written and retrieved from sqlite
by haukex (Archbishop) on May 15, 2017 at 15:31 UTC

    You may need to binmode your files, especially on Windows. Try open (my $MYFILE,'<:raw', ... and open (my $OUTPUT, '>:raw', ... (which is the equivalent of binmode $filehandle;).

    Update: Added a bit more info.

Re: corruption of jpg written and retrieved from sqlite
by huck (Prior) on May 15, 2017 at 15:34 UTC
      exactly right!! thanks to the IMMEDIATE responses!