1

This code is working (using Heroku):

<?php
    $db = parse_url(getenv("DATABASE_URL"));
    $pdo = new PDO("pgsql:" . 
        sprintf("host=%s;port=%s;user=%s;password=%s;dbname=%s",
            $db["host"],
            $db["port"],
            $db["user"],
            $db["pass"],
            ltrim($db["path"], "/")
    ));

    $sql = 'SELECT "Image" AS data FROM mylinks where id = 2;';
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data = $row['data'];
    }
    $stmt->closeCursor();

    file_put_contents("abc.jpg", $data);
    $image = 'abc.jpg';
    $imageData = base64_encode(file_get_contents($image));
    $src = 'data: '.mime_content_type($image).';base64,'.$imageData;
    echo '<img src="', $src, '">';
?>

If I refuse to write the image file and process the image data directly like this:

...
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data = $row['data'];
    }
    $stmt->closeCursor();

    $imageData = base64_encode($data);
    $src = 'data: jpeg;base64,'.$imageData;
    echo '<img src="', $src, '">';
?>

It doesn't work. I only get this empty img tag:

<img src="data: jpeg;base64,">

It of course makes no sense to write a file and the read it again. There must be a smart way to process the $data directly but I wasn't able to figure that out. Can anybody help?

Steffen
  • 601
  • 1
  • 5
  • 5
  • 1
    Does this answer your question? [Displaying a Base64 images from a database via PHP](https://stackoverflow.com/questions/16262098/displaying-a-base64-images-from-a-database-via-php) – B001ᛦ May 30 '20 at 15:40
  • Thanks, but no. It's hard to add something here without repeating my question. – Steffen May 30 '20 at 19:35
  • **Solution:** $data is a stream, not a string. So one has to handle it like this: `rewind($data); $imageData = base64_encode(stream_get_contents($data));` – Steffen May 31 '20 at 09:13
  • You can always share and post answer to your own question and also earn reputation – B001ᛦ May 31 '20 at 17:27
  • I know, but in this case I can't because @JohnConde closed this question. – Steffen May 31 '20 at 22:51

0 Answers0