Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  75] [ 1]  / answers: 1 / hits: 73328  / 14 Years ago, thu, july 15, 2010, 12:00:00

I need to send a base64 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 image/jpeg content-type to the browser.
Example in php:



$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);


Clientside, I'm calling:



var img     = new Image();
img.src = http://www.myserver.com/generate.php;
img.onerror = function(){alert('error');}
$(img).appendTo(document.body);


That does not work for some reason. onerror always fires. Watching the FireBug Network task for instance, tells me that I'm receiving the correct header information and a correct value of transfered bytes.



If I send that data as Content-type: text/plain it works, the base64 string is shown in the browser (if I call the script directly). Copying and pasting that output into the src of a <img> element shows the image as expected.



What am I doing wrong here?



Solution



Thanks Pekka 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.


More From » php

 Answers
6

In this case, there is no reason to base64 encode the image data in the first place. What you want to emit is plain old image data.



Just pass through the JPEG image as-is.



The only way this would make sense to me is if you grabbed the output of generate.php via an AJAX call, and put the result into the src property directly. That should work (although not in IE < 8, but I'm sure you know that). But if you can call generate.php directly as the image's source, I don't see the need for this.


[#96218] Tuesday, July 13, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;