I have a PHP script that generates a PNG captcha(set by Content-Type header).It can be embedded in an HTML page by just using img. I want to convert that image to base64 format for displaying.How do I go about doing that ?

Using the normal method for encoding as given on Wikipedia's article(Click Here) doesn't work.

Dani AI

Generated

Short answer for : you need the raw PNG bytes (not the Content-Type header or any extra output) and then base64-encode those bytes and use a data URI in the image src. As noted, reading a saved PNG and encoding it works for static files; for an on-the-fly captcha you must either (A) make the captcha generator return the encoded string or (B) fetch the binary server-side and encode it before sending it to the page.

A common server-side pattern (modify the captcha script so it can return base64) is to capture the PNG output into a buffer, base64-encode that buffer, then return a data:image/png;base64,... string (or JSON containing that string). Example outline:

// inside your captcha generator when asked for base64
ob_start();
// render the PNG into output (e.g. imagepng($im); )
$png = ob_get_clean();
echo 'data:image/png;base64,' . base64_encode($png);

Client-side you can then assign that string to an IMG element (or request it via AJAX and set img.src).

Troubleshooting checklist (most common reasons "it didn't work"):

  • Verify the captcha script actually produces a valid PNG by opening its URL directly.
  • Disable or fix PHP notices/whitespace — any extra bytes will corrupt the PNG stream.
  • When returning base64, do not send the image/png header; send plain text or JSON.
  • Be aware of tradeoffs: base64 increases payload ~33% and prevents independent caching; strict CSP or very old browsers can block or limit data: URIs.
  • If the captcha lives on another domain, fetch it server-side (cURL) and encode, or enable CORS and return the base64 string.

Embedding as base64 is handy for single-request pages or AJAX flows, but for resilience and caching a normal image URL often remains the simplest choice.

Member Avatar for Member #949455

I have a PHP script that generates a PNG captcha(set by Content-Type header).It

I haven't done this before but you can try this.

Have you try to put the data on an xml element?

<?php
$img = file_get_contents('captcha.png');
$imgdata = base64_encode($img);  
?>

Then your xml tags should be like this:

<image width="25" height="25">data:image/png;base64,imageData</image>

or you can take a look at this:

http://shashankbhide.wordpress.com/2011/11/15/base64-encoded-image-based-captcha-control/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.