To prevent any problems with encoding you could use hexadecimal or base64 input to save and retrieve data to the database:
<?php
$dbconn = pg_connect( 'dbname=foo' );
$data = file_get_contents( 'image1.jpg' );
$escaped = bin2hex( $data );
pg_query( "INSERT INTO gallery (name, data) VALUES ('Pine trees', decode('{$escaped}' , 'hex'))" );
$res = pg_query("SELECT encode(data, 'base64') AS data FROM gallery WHERE name='Pine trees'");
$raw = pg_fetch_result($res, 'data');
header('Content-type: image/jpeg');
echo base64_decode($raw);
?>