简体   繁体   English

图像到base64编码的问题-PHP

[英]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 PHP v5.6.2

I tired copying the $src value in debug and pasted in img src value. 我厌倦了在调试中复制$ src值并粘贴到img src值中。 still its not showing up. 仍然没有出现。

what did i missed here?. 我在这里错过了什么?

thanks in advance 提前致谢

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

here you say to the browser i will send you an jpeg image , then: 在这里,您对浏览器说, i will send you an jpeg image ,然后:

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

here you send HTML. 在这里您发送HTML。

because you said it was a jpeg image, the browser will try to render your html as jpeg . 因为您说的是jpeg图像,所以浏览器将尝试将html呈现为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.) 由于基于ascii文本的HTML格式与基于二进制的jpeg格式完全不兼容 ,因此浏览器在尝试渲染图像时会严重失败,并会因某些错误而失败(可能是image is corrupt或类似的情况。)

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: 您可以修复Content-Type标头以指定您正在发送HTML,然后浏览器将(可能成功!)尝试这样渲染它,例如:

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

or you can modify your code to actually send the image as jpeg, eg: 或者您也可以修改代码以将图像实际发送为jpeg,例如:

<?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.) (顺便说一下,base64编码的jpeg图像将比原始jpeg图像大约33%,因此,如果您想要快速的页面加载,或者想节省带宽,或者想在ram上节省,请使用readfile()与嵌入式base64方法相比,对于服务器和客户端而言,速度更快,所需带宽更少,RAM更少。)

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() 注意:最好使用全地址域中的路径,如果要使用路径,请使用readfile()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM