php - 在 PHP 中显示来自 PostgreSQL 数据库的图像

标签 php postgresql png bytearray

我想在 PHP 文件中显示来 self 的 PostgreSQL 数据库的图像。 在尝试了很多不同的可能性之后,我并没有走得太远。 这是我所做的:

上传:

echo "<div>".
    "<table border=\"1\" cellpadding=\"3\">".
       "<form action=\"test2.php\" method=\"post\" enctype=\"multipart/form-data\">".
         "<tr>".
           "<td>".
             "<input type=\"file\" name=\"file\" id=\"file\">".
             "<input class=\"button\" type=\"submit\" name=\"submit\" value=\"Submit\">".
           "<tr>".
         "</tr>".
      "</form>".
     "</table>".
   "</div>"; 

显示:

if(isset($_FILES['file'])) //file uploaded
{
  $file_raw = file_get_contents($_FILES['file']['tmp_name']);
  $file     = pg_escape_bytea($file_raw);
  //Here is Code to insert into Database but just to test, I try it directly:

  header('Content-Type: image/png');
  echo pg_unescape_bytea($file);
}

我已经在一个额外的文件中有了显示部分等等,但这些是你需要知道的基本信息。

我不会显示任何图像,只有浏览器中的这个“损坏的图像”图标。 这里有什么问题?我该如何解决这个问题? 谢谢!

最佳答案

处理简单:

<?php 
// Connect to the database
$dbconn = pg_connect( 'dbname=foo' );

// Read in a binary file
$data = file_get_contents( 'image1.jpg' );

// Escape the binary data to avoid problems with encoding
$escaped = bin2hex( $data );

// Insert it into the database
pg_query( "INSERT INTO gallery (name, data) VALUES ('Pine trees', decode('{$escaped}' , 'hex'))" );

// Get the bytea data
$res = pg_query("SELECT encode(data, 'base64') AS data FROM gallery WHERE name='Pine trees'");  
$raw = pg_fetch_result($res, 'data');

// Convert to binary and send to the browser
header('Content-type: image/jpeg');
echo base64_decode($raw);
?>

关于php - 在 PHP 中显示来自 PostgreSQL 数据库的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210612/

相关文章:

ruby-on-rails - 如何 rake 数据库 :migrate on a Heroku staging pipeline?

css - cookies 图案喜欢

Delphi 组件中的 PNG 图像集合

php - 如何在sql中选择季度数据

php - 从第一个表中选择所有内容,计算第二个表中 ID 的实例数

php - 使用 PHP 检查数据库中是否存在逗号分隔值

mysql - PostgreSQL 上的公式查询

php - 从 Wordpress 中删除后删除插件数据

sql - 有什么办法可以在 postgreSQL 中将假期与工作日分开吗?

c++ - Qt - 将 JPEG 转换为 PNG 不提供相同的图像