Jump to content

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.

 

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

Some browsers support the data protocol. But I wouldn't rely on it.

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.