Hishan_98
Hishan_98

Reputation: 212

Cannot display base64 decoded image in a HTML tag using PHP

Why I cannot display an image inside an HTML tag ?.

<?php
session_start();

$ch = curl_init( 'https://mighty-inlet-78383.herokuapp.com/api/hotels/imagedata');
curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => TRUE
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    die(curl_error($ch));
    echo 'No responce';
}

// Decode the response
$responseData = json_decode($response, true);

// get data from api to json
foreach($responseData AS $response) {

    $hotelImage = $response['hotelImage'];

    $imgdecord = base64_decode($hotelImage). "\n"; 

    if(empty($email)){
        echo "No responce from server";
    }
    else{
        echo '<br>';
        echo'
            <html>
                <head></head>
                <body>
                <img src="data:image/png;base64,' . $imgdecord . '" />
                </body>
            </html>    
        ';
        }
}

?>

It shows below result in the browser

���z�C�ZM�]y�eb��3K�� �� �<~_^%�HW � t}��-l��)Z/�2H����.r�M���g�q��kޭ��q�і��/�P���W��.�b�$/�a������O,U�S����5��\mr��8�ӓPs|�C|� u��W~l��t�l-��������9����%͓��E��ַ�5�]z�� �O ���`��Tl���GO��oQ�E�����y�o�l�,児

My API returns values like this

[
    {
        "_id": "5e8f2e81c15e30001791379e",
        "name": "harlyRox",
        "email": "[email protected]",
        "phone_number": 713677319,
        "hotelImage": "iVBORw0KGgoAAAANSUhEUgAABVYAAAMACAYAAADPPjzCAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAP+6SURBVHhe7J0FYB3Htf6P0GLJkm1JlkySGWLG2I7DDG3StEnhFd//vcJrX5k5hddX5vaVU06TtkmaNE2TNszMTHYSc8ys
},..
]

Upvotes: 0

Views: 533

Answers (1)

Hishan_98
Hishan_98

Reputation: 212

it works when I remove this line

$imgdecord = base64_decode($hotelImage). "\n"; 

and change this HTML tag to

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

as @LawrenceCherone mentioned above

Upvotes: 1

Related Questions