php – 在Postgre bytea列中显示存储为二进制的图像
发布时间:2020-12-13 15:58:45 所属栏目:PHP教程 来源:网络整理
导读:我被困了好几个小时.在网上找到的解决方案很少,但似乎没有人帮助我.我有问题在浏览器上使用 PHP从浏览器中显示图像,从Postgres DB获取列类型为bytea的图像.我确定我在这里遗漏了一些东西.所以一些指导真的很感激.所以我有以下代码: $prod = new Product();$
我被困了好几个小时.在网上找到的解决方案很少,但似乎没有人帮助我.我有问题在浏览器上使用
PHP从浏览器中显示图像,从Postgres DB获取列类型为bytea的图像.我确定我在这里遗漏了一些东西.所以一些指导真的很感激.所以我有以下代码:
$prod = new Product(); $prod->display_latest_product(); if( $prod->exists() ){ $products = $prod->data(); foreach($products as $product){ echo $product->id; echo $product->binarydata; /* Solution below: I only get one image with broken link */ header('Content-type: image/png'); echo pg_unescape_bytea($product->binarydata); /* Solution below: I only get one image with broken link */ header('Content-Type: image/png'); $data=fgets($product->binarydata); print(pack('H*',$data)); /* bin2hex() expects parameter to be string but resource given */ echo bin2hex($product->binarydata); /* Solution below: I only get one image with broken link */ $image = stripcslashes($product->binarydata); header("Content-Type: image/png"); print($image); } } 我很欣赏这方面的一些解释,因为我在研究和阅读后仍然感到困惑. 解决方法
最后我找到了做到这一点的方法.基于我在
Handling Binary Data with PDO中找到的内容,因为我使用PDO来读取DB中的列.
所以我将这两行放在foreach循环中: header("Content-Type: ".$product->mimetype); fpassthru($product->binarydata); 我的文件显示得很好.由于@Musa指出我一次只能打印一张图像,所以我将使用img和src =“thepage.php?img = xx”来显示图像.我正在开发电子商务应用程序,因此不确定这是否会影响性能,因为将加载大量图像.欢迎提出任何意见或建议.无论如何,我希望这可以帮助那些有同样问题的人. 关于fpassthru的文件是here. 编辑::解决方案 所以我终于得到了解决我在下面评论中定义的问题的真正解决方案.而这次它根本不涉及PHP标头. foreach($products as $product){ ob_start(); // Let's start output buffering. fpassthru($binarydata); //This will normally output the image,but because of ob_start(),it won't. $contents = ob_get_contents(); //Instead,output above is saved to $contents ob_end_clean(); //End the output buffer. $dataUri = "data:image/png;base64," . base64_encode($contents); echo "<img src='$dataUri' />"; } 我已经得到了解决方案here.并且根据该线程中的注释,诀窍实际上是在缓冲. ob_start必须与ob_end_clean()配对使用.希望这可以帮助那里的人们.谢谢. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |