Abdennour
Abdennour

Reputation: 75

What is the correct way of displaying base64 image from database to php page?

I cannot figure out why my image is not displaying in my index.php page.

I use PDO to connect and use the database, but I faced some weird problem that has never happened to me before. The image that I stored in my database as blob type is not displaying in my index.php page.

Here's my code:

<?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));   
        }           
    }    
?>

This I use to display images on my images div tag:

<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>

Upvotes: 1

Views: 576

Answers (1)

nahuelhds
nahuelhds

Reputation: 532

I would store the image directly encoded in base64 an also its extension for proper display.

IMPORTANT The content field has to be TEXT type in your database, otherwise you won't store the data properly and you won't be able to get it as you should

<?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>

Upvotes: 1

Related Questions