Jump to content

Displaying Base64 Images


crwork

Recommended Posts

Question regarding the decoding and display of base64 images.

 

I have a site that will display a user avatar at the top of the content page. There is a web service I'm calling that receives a user ID as input and retrieves a base64 encoded image.

 

I'm getting the base64 image back successfully with this code:

 

//Get base64 image from XML return in cURL resource
$userImageData = curl_exec($ch);

//Extract the base64 image

$userImageXML = new SimpleXMLElement($userImageData);
$userImage64 = $userImageXML->return;

//Decode the base64 image
$imgDecoded = base64_decode($userImage64);

 

What isn't working is when I display the variable for the decoded image, $imgDecoded, in an IMG tag. It just shows a long string of odd characters.

 

However, what DOES work is if I display the encoded base64 image that has not been decoded, variable $userImage64:

echo "<img src=data:image/png;base64,$userImage64 title='User Avatar' >";

 

I'm confused, and this is probably a simple explanation, as to why the decoded base64 image, variable $imgDecoded won't display in the IMG tag.

 

I feel like I'm missing something basic, but I'm a bit stuck on this one...

Link to comment
https://forums.phpfreaks.com/topic/269315-displaying-base64-images/
Share on other sites

I'm confused, and this is probably a simple explanation, as to why the decoded base64 image, variable $imgDecoded won't display in the IMG tag.

 

You can't just stick raw image data into an <img> tag. You would have to write the decoded data ($imgDecoded) to a file, then reference that file in the <img> tag.

 

Did you really just use an MSDN link to justify yourself?

Sure did: MSDN is pretty great, actually. There's also Wikipedia and the RFC if you'd rather read those.

 

Also, I retract my statement about not relying on it. Seems browser support has increased to nearly everyone.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.