【问题标题】:What is the correct way of displaying base64 image from database to php page?将base64图像从数据库显示到php页面的正确方法是什么?
【发布时间】:2019-05-10 16:10:29
【问题描述】:

我不知道为什么我的图片没有显示在我的index.php 页面中。

我使用 PDO 连接和使用数据库,但我遇到了一些以前从未发生过的奇怪问题。我以 blob 类型存储在数据库中的图像未显示在我的 index.php 页面中。

这是我的代码:

<?php    
    $dsn = 'mysql:host=localhost;dbname=website;charset=utf8mb4';

    $pdo = new PDO($dsn, 'root', '');

    if ( isset($_POST['upload']) ) 
    {         
        $file = addslashes(file_get_contents($_FILES['image']['tmp_name']));

        if ( !empty($file) ) 
        {               
            $sql = " INSERT INTO images(name) VALUES (:name) ";
            $pdo->prepare($sql)->execute(array('name' => $file));   
        }           
    }    
?>

我用它在我的 images div 标签上显示图像:

<div class="images" id="Images">                
    <?php      
        $sql = " SELECT * FROM images ";
        $result = $pdo->query($sql);

        if ( $result->rowCount() > 0 ) 
        {              
            while ( $row = $result->fetch() ) 
            {                    
                echo '<img src="data:image/jpeg;charset=utf-8;base64,' .base64_encode($row['name']). '" alt="Binary Image"/>';   
            }   
        }                      
    ?>   
</div>

【问题讨论】:

标签: php html


【解决方案1】:

我会将图像直接存储在 base64 编码中也是正确显示的扩展

重要 content 字段在您的数据库中必须是 TEXT 类型,否则您将无法正确存储数据并且您将无法按预期获取它

<?php

$dsn = 'mysql:host=localhost;dbname=website;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '');

if (isset($_POST['upload'])) {
    // Get the image and convert into string
    $img = file_get_contents($_FILES['image']['tmp_name']);

    // Encode the image string data into base64
    $content = base64_encode($img);
    // Get the extension
    $extension = strtolower(end(explode('.', $_FILES['image']['name'])));
    if (!empty($content)) {
        $sql = " INSERT INTO images(content, extension) VALUES (:content, :extension) ";
        $pdo->prepare($sql)->execute(array('content' => $content, 'extension' => $extension));
    }
}

// Later in your code
?>
<div class="images" id="Images"></div>
    <?php
    $sql = " SELECT * FROM images ";
    $result = $pdo->query($sql);
    if ($result->rowCount() > 0) {
        while ($row = $result->fetch()) {
            echo "<img src='data:image/{$row['extension']};charset=utf-8;base64,{$row['content']}' alt='Binary Image'/>";
        }
    }
    ?>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2015-05-09
    • 2016-08-26
    相关资源
    最近更新 更多