【问题标题】:In PHP, how I show various images from a BLOB field in the database with the HTML content?在 PHP 中,如何使用 HTML 内容显示来自数据库中 BLOB 字段的各种图像?
【发布时间】:2011-09-11 01:26:38
【问题描述】:

我使用 BLOB 字段将图像存储在数据库中(我使用的是 SQLite)。现在我想将此图像恢复为 HTML 页面并在那里显示图像。

我可以从数据库中的图像中检索二进制数据,但是我可以做些什么来将这些数据转换为图像并显示在页面中?目前我想在表格的字段中显示图像。

【问题讨论】:

  • 很难选择最佳答案,但现在我知道如何解决这种情况了。谢谢大家。

标签: php image sqlite blob transform


【解决方案1】:

我会说两种选择:

  1. 您创建了一个返回图像数据的脚本。然后<img src="-field 调用该脚本。
  2. 您直接通过data url 提供图像数据。

两者各有利弊。对于第一个解决方案,您必须为图像创建一个新脚本。如果图像很大,第二种方法会使您的页面膨胀。

由于已经有图像脚本方法的示例,这里是一些数据 URI 的代码片段:

<?php
function data_uri($content, $mime) 
{  
  $base64   = base64_encode($content); 
  return ('data:' . $mime . ';base64,' . $base64);
}
?>

<img src="<?php echo data_uri($content,'image/png'); ?>" />

您需要根据您的图像设置mime-type,image/png用于PNG图像,image/jpeg用于JPG文件等,请参阅here for a list

【讨论】:

    【解决方案2】:

    您可以创建一个简单的 image.php 页面来查询您的数据库,然后打印出与图像相关的内容类型并将二进制数据吐到屏幕上。因此,在您的表中,您将拥有&lt;img src=image.php?id=something /&gt;,然后您将在 image.php 页面中使用该 id 进行数据库查找,检索二进制数据,并在打印内容类型后将其打印到屏幕上标题。

    image.php:

    <?php
    
    header('Content-type: image/jpeg');
    
    //DO SQL NINJA STUFF HERE
    
    echo mysql_result($result,0,"file_content");
    

    ?>

    【讨论】:

      【解决方案3】:

      @uscere90 是对的,但一个示例可能会有所帮助(PNG 图像示例):

      <?php
        header("Content-type: image/png");
        echo $image_data;
      ?>
      

      【讨论】:

        【解决方案4】:

        通常这是通过创建一个包装脚本或函数来完成的,该脚本或函数检索 BLOB 并将其与适当的内容标头一起用作&lt;img src=''&gt;

        这样做还使您能够根据 PHP 确定的其他身份验证因素来交付或不交付图像。例如,如果用户没有查看图像的权限,您可以在其位置显示一些默认或阻止图像。

        // File getimg.php
        // Retrieve the image blob specified by $_GET['imgid'] from the database
        
        // Assuming your blob is now in the variable $image...
        header("Content-type: image/jpeg");
        // Just echo out the image data
        echo $image;
        exit();
        

        现在在您的 html 中:

        <img src='getimg.php?imgid=12345' alt='this is your img from the database' />
        

        【讨论】:

          【解决方案5】:

          你可以滥用data: 协议,但相信我,如果你能避免它,你不会想要这样。通常,您创建一个单独的 php 脚本来提供图像,因此在脚本 1 中:

           <img src="/myimagescript.php?id=1234">
          

          在 myimagescript.php 中:

          //get the data from the database somehow (mysql query et al.)
          //let's assuma the data is in $data
          header('Content-Type: image/jpeg');//alter for png/gif/etc.
          echo $data;
          

          【讨论】:

          • 哇,你在同一秒提交了一个几乎与我相同的答案。
          • 确实看到了,0 seconds ago 对于两者来说,古雅:)
          猜你喜欢
          • 2019-07-05
          • 2012-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-12
          • 2014-07-05
          • 1970-01-01
          相关资源
          最近更新 更多