Problem displaying images saved as blob images

147 views Asked by At

am having an issue displaying images stored as blob in my database, as the images doesn't display rather is shows crazy characters and symbols, i tried to change the tags for the php but with no avail. Help and here is my code: Note that i want all types of images to be saved as blob (jpg, jpeg, gif, svg, png) - thanks in advance

    <?php
        include 'include/connect.php';
        $sql = "SELECT * FROM room_details ORDER BY id ASC LIMIT 2, 1;";
        $result = mysqli_query($conn, $sql);
        if (mysqli_num_rows($result) > 0) {
          while($row = mysqli_fetch_assoc($result)) {

    ?>


        <div class="room-thumb"><?php echo '<img alt="room 3" class="img-responsive" src="data:image;base64,'.$row['image'].'">'; ?>
            <div class="mask">
              <div class="main">
                <h5><?= $row['room_type']; ?></h5>
                <div class="price"><?= $row['room_name']; ?><span>a night</span></div>
              </div>

                <a href="room-detail.html" class="btn btn-primary btn-block">Read More</a>
              </div>
          </div>

          } ?>
1

There are 1 answers

1
AndrewL64 On BEST ANSWER

Since the blob url is decoded with base64, you need to encode it first. You can use either JavaScript or PHP to do this.

JavaScript:

With JavaScript, you can just use the atob() function to encode your base64 url like this:

<script>
  var x = <?php echo $row['image'] ?>
  document.getELementById("code").innerHTML = atob(x);
</script>

<div class="room-thumb"><?php echo '<img alt="room 3" class="img-responsive" src="data:image;base64,' ?><span id="code"></span><?php echo '">'; ?>
    <!-- DIV CONTENT HERE -->
</div>

However, as stated in this other SO thread, it would be a better approach if you use PHP itself or other JavaScript approaches (mentioned in that same thread) to retrieve and encode the base64 url as the above approach is not secure.


PHP:

With PHP, you can either encode the base64 url before outputting it into your HTML like this:

<?php echo '<img alt="room 3" class="img-responsive" src="data:image;base64,' . base64_encode(.$row['image']).'">'; ?>

Or you can create a new php file, encode the PHP in that file and then echo the encoded base64 url to your HTML like this:

    <!-- PHP file -->
    <?php
      $id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? intval($_GET['id']) : 0;
      $image = base64_encode(getImageFromDatabase($id)); // your code to fetch the image
    
      header('Content-Type: image/jpeg');
      echo $image;
    ?>

    <!-- HTML -->
    <img src="image.php?id=<?php echo $image_id; ?>" />


Check out the accepted answer in this other SO thread for a more in-depth explanation of the above two PHP approaches.