Search code examples
php

How to decode a Base64 encoded image?


I have this database that contains images as strings. Those strings look something like this:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...

I need to create a link that will display this image. Like something.com/?id=27 is an image. All the images are in jpeg format. Here's what I've tried but didn't work:

<?php
  $host = "smth";
  $user = "smth";
  $pass = "smth";
  $db_name = "smth";
  $dbh = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
  $dbh->exec("SET NAMES utf8");
  $q = $dbh->prepare("select content from img where id = :id");
  $q->execute(array(':id'=>$_GET['id']));
  $row = $q->fetch(PDO::FETCH_BOTH);
  header("Content-type: image/jpeg");
  echo $row['content'];
?>

The data is being fetched correctly but the image is not displayed.

I need to be able to use this link like this <img src="mysite.com?id=21" /> and I do NOT want this solution: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABA..." />

Thanks!


Solution

  • The solution to your problem is here:

    How to decode a base64 string (gif) into image in PHP / HTML

    Quoting that source but modifying:

    In the case you strip out the first case and choose to decode the string, you should add this before echoing the decoded image data:

    header("Content-type: image/gif");
    $data = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
    echo base64_decode($data);
    

    In the second case, use this instead:

    echo '<img src="data:image/gif;base64,' . $data . '" />';
    

    The second case is bad because the browser does not perform caching if the same image is shown on multiple pages.