Note that there are some explanatory texts on larger screens.

plurals
  1. POSending/Displaying a base64 encoded Image
    primarykey
    data
    text
    <p>I need to send a <code>base64</code> encoded string to a client. Therefore, I'm opening and reading an image file on the server, encode it and send that data along with the <code>image/jpeg</code> content-type to the browser. <strong>Example in php:</strong></p> <pre><code>$image = $imagedir . 'example.jpg'; $image_file = fopen($image, 'r'); $image_data = fread($image_file, filesize($image)); header("Content-type: image/jpeg"); echo 'data:image/jpeg;base64,' . base64_encode($image_data); </code></pre> <p><strong>Clientside</strong>, I'm calling:</p> <pre><code>var img = new Image(); img.src = "http://www.myserver.com/generate.php"; img.onerror = function(){alert('error');} $(img).appendTo(document.body); </code></pre> <p>That does not work for some reason. <code>onerror</code> always fires. Watching the FireBug <code>Network task</code> for instance, tells me that I'm receiving the correct header information and a correct value of transfered bytes.</p> <p>If I send that data as <code>Content-type: text/plain</code> it works, the <code>base64</code> string is shown in the browser (if I call the script directly). Copying and pasting that output into the <code>src</code> of a <code>&lt;img&gt;</code> element shows the image as expected.</p> <p>What am I doing wrong here?</p> <p><strong>Solution</strong></p> <p>Thanks <code>Pekka</code> for pointing me on my mistake. You don't need (you can't!) encode that binary image data as base64 string in that kind of approach. Without base64 encoding, it just works.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload