dongmou9260 2012-06-30 11:43
浏览 38
已采纳

使用php从postgresql中显示图像(bytea)

I have a postgres database with stored images 'bytea' type and I try to display them into a browser with PHP. I found the way to display one of them but I can't make it for more than one. The code I use is the following:

File Name - display_image.php

$conn = pg_connect("dbname=test user=postgres password=postgres");

$temp = '/home/postgres/tmp.jpg';

$query = "select lo_export(image, '$temp') from map ";
$result = pg_query($query);

if($result)
{
    while ($line = pg_fetch_array($result))
    {
        $ctobj = $line["image"];
        echo "<IMG SRC=show.php> </br>";

    }

}
else { echo "File does not exists."; }
pg_close($conn);

File Name - show.php

header("Content-type: image/jpeg");
$jpeg = fopen("/home/postgres/tmp.jpg","r");
$image = fread($jpeg,filesize("/home/postgres/tmp.jpg"));
echo $image;

The problem seems to be the "tmp.jpg" virtual file which displays only one image. If the result of the query is 7 images then it displays 7 times the same image within a while loop. How can I solve this? Thanks for the interest!

  • 写回答

1条回答 默认 最新

  • doulu3808 2012-09-05 09:46
    关注

    I did this some time ago for bytea.

    You need to run your bytea data through pg_unescape_bytea. See http://php.net/manual/en/function.pg-unescape-bytea.php

    Basically your SQL query returns the bytea field in an escaped format.

    However this is not what you are doing. And so the above is just for the next poor sap who comes here looking for bytea help. Please amend to note you are using LOB's not BYTEA's.

    Also note that your code there is not concurrency safe. If two users request different images, my guess is that you will get both users getting different images. For this reason you should add the oid to the retrieval url, and name your file /tmp/$oid.jpg where $oid is the oid of the large object. You will need to retrieve that info (I believe it looks like it is stored in the image field of map?). On the other hand that assumes that all files are essentially public. if that's not the case, you want to move everything into the show_image.php and clean up when you are done.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的
  • ¥15 硬件IIC从模式的数据发送,中断数据的接收,不能用HAL库(按照时序图)
  • ¥20 QAxWidget上显示一个word文档后,如何直接在该QAxWidget上修改和保存word文档
  • ¥15 Simulink仿真报错,请问如何解决
  • ¥20 宝塔面板无法添加Node项目,一直处于正在添加脚本页面