在PHP中显示来自PostgreSQL数据库的图像 [英] Display image from PostgreSQL database in PHP

查看:74
本文介绍了在PHP中显示来自PostgreSQL数据库的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在PHP文件中显示来自PostgreSQL数据库的图像. 在尝试了许多不同的可能性之后,我走的并不远. 这是我的工作:

I want to display an image from my PostgreSQL database in a PHP file. After trying a lot of different possibilities, I don't get very far. Here is what I do:

上传:

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);
}

我已经在一个额外的文件中包含了显示部分,依此类推,但这是您需要了解的基本信息.

I already have the display part in an extra file and so on, but these are the essential information you need to know.

我不会显示任何图像,只是从浏览器显示此残破图像"图标. 这是怎么了我该如何解决? 谢谢!

I wont get any image displayed, just this "Broken Image" icon from the browser. What is wrong here? How can I solve this? Thank you!

推荐答案

简单处理:

Simple handling:

<?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中显示来自PostgreSQL数据库的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆