Habeeb
Habeeb

Reputation: 352

Image to base64 encoding issue - PHP

<?php
   header("Content-type: image/jpeg;charset=utf-8'");
   $path = 'example/source.jpg';
   $da = file_get_contents($path);

   $base64 = base64_encode($da);
   $src = 'data:image/jpeg;charset=utf-8;base64,'.$base64;
   echo '<img src="'.$src.'">';

?>

php v5.6.2

I tired copying the $src value in debug and pasted in img src value. still its not showing up.

what did i missed here?.

thanks in advance

Upvotes: 0

Views: 1075

Answers (2)

hanshenrik
hanshenrik

Reputation: 21665

header("Content-type: image/jpeg;charset=utf-8");

here you say to the browser i will send you an jpeg image, then:

echo '<img src="'.$src.'">';

here you send HTML.

because you said it was a jpeg image, the browser will try to render your html as jpeg. since the ascii text-based HTML format is completely incompatible with the binary based jpeg-format, the browser will fail horribly when trying to render your image, and fail with some error (probably image is corrupt or something like that.)

you can either fix your Content-Type header to specify that you're sending HTML, then the browser will (probably successfully!) try to render it as such, eg:

header("Content-type: text/html;charset=utf-8");

or you can modify your code to actually send the image as jpeg, eg:

<?php
   header("Content-type: image/jpeg");
   $path = 'example/source.jpg';
   readfile($path);

(btw a base64 encoded jpeg image will be about 33% larger than just the raw jpeg image, so if you want a fast pageload, or you want to save up on bandwidth, or you want to save up on ram, using readfile() is faster, requires less bandwidth, and requires less ram, both for the server and the client, compared to your embedded base64 approach.)

Upvotes: 1

ttrasn
ttrasn

Reputation: 4851

So maybe your problem is in your mime type. then try this code two solve:

$path = 'domain.com/example/source.jpg';

$content = file_get_contents($path);
$file_info = new \finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($path));
$base64 = base64_encode($content);
$src = 'data:'.$mime_type.';charset=utf-8;base64,'.$base64;
echo '<img src="'.$src.'">';

Note: its better to use path from full address domain, if you want to use from path use readfile()

Upvotes: 0

Related Questions