1

I need to display an image which is in Base64 format. When I build the img tag in PHP it doesn't show the image (just the defualt 'broken image' icon). When I view the page source and click on the Base64 data is shows the picture as expected. Also, if I copy and paste the page source and save it as an HTML file it displays as expected. I also tried a random image and that worked however as my image works from a .html file I assume it is OK and should work?

The .php code:

header('content-type: text/html');

...

echo "<html><head></head><body>";
echo "Name = $name<br/>";
echo "<img src=\"data:image/jpg;base64,$photo\"/>";
echo "</body></html>";

The HTML from View Source:

<html>
<head></head>
<body>Name = Andrea Pilipczuk<br/>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAyADIAA...{too big to fit here].../9k="/>
</body>
</html>

EDIT:

This didn't come up in View Source but digging around Chrome, I inspected the image element and found at the end was "9k=�������". Is this some kind of padding? When I edited the element to remove these the image showed up as expected.

The following code removes the random characters and displays the image correctly but seems a bit hacky, would obviously prefer to solve the underlying issue.

$unpadded = explode("=", $photo);
$padding = strlen($unpadded[0]) % 3;
$padded = $unpadded[0];
while ($padding > 0) {
  $padded .= "=";
  $padding--;
}
echo "<img src=\"data:image/jpeg;base64,$padded\"/>";
Dre
  • 543
  • 1
  • 4
  • 17

0 Answers0