php – 在Postgre bytea列中显示存储为二进制的图像

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 在Postgre bytea列中显示存储为二进制的图像脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我被困了好几个小时.在网上找到的解决方案很少,但似乎没有人帮助我.我有问题在浏览器上使用 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()配对使用.希望这可以帮助那里的人们.谢谢.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 在Postgre bytea列中显示存储为二进制的图像全部内容,希望文章能够帮你解决php – 在Postgre bytea列中显示存储为二进制的图像所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。