-2

I want to display a image that is encoded with base64_encode. The image is fetching from mysql db based on the id parameter passed through the URL. The Content-type has been set. Say i have a code in index.php file and i am hitting that file in browser with url localhost:8080/products_images/index.php?id=1000

header('Content-Type:image/png');
if (isset($_GET['id'])) {
$id = $_GET['id'];
} 

$sql = "SELECT image FROM table WHERE id = ".(int)$id;

$image = $dbInstance->getArray($sql);
unset($sql);
echo '<img src="data:image/png; base64,'.$image[0]['image'].'"/>';

Instead of displaying the image on a browser, it says The image “localhost:8080/products_images/index.php?id=1000” cannot be displayed because it contains errors.

I know its happening because on a browser DOM, i can clearly see the image tag appearing like following <img src="localhost:8080/products_images/index.php?id=1000"> Instead of showing the encoded string to img src tag, its showing the whole URL. Any help would be appreciated!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
faran
  • 83
  • 7

1 Answers1

-3

To send the image to the client, you might try to load the image from the string with imagecreatefromstring function then send it to the client with imagepng function, it should give you something like that:

<?php
    $data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
    . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
    . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
    . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';

    $data = base64_decode($data);
    $im = imagecreatefromstring($data);

    if ($im !== false) {

        header('Content-Type: image/png');

        // Send the image
        imagepng($im);

        imagedestroy($im);

    } else {

        echo 'An error occurred.';

    }
?>

I got it from the php doc

Paragoumba
  • 88
  • 1
  • 10