如何将图像从URL转换为Base64编码?
当前回答
容易:
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);
请记住,这将使数据扩大33%, 如果文件的大小超过了memory_limit,就会出现问题。
其他回答
非常简单且常用的:
function getDataURI($imagePath) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->file($imagePath);
return 'data:' . $type . ';base64,' . base64_encode(file_get_contents($imagePath));
}
// Use the above function like below:
echo '<img src="' . getDataURI('./images/my-file.svg') . '" alt="">';
echo '<img src="' . getDataURI('./images/my-file.png') . '" alt="">';
注意:文件的MIME类型将自动添加(从PHP文档中获得帮助)。
下面是一个使用cURL调用的例子…这比file_get_contents()函数更好。当然,使用base64_encode()。
<?php
$url = "http://example.com";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
?>
<img src="data:image/png;base64,<?php echo base64_encode($output);?>">
以防你(出于某种原因)无法使用curl或file_get_contents,你可以使用以下方法:
$img = imagecreatefrompng('...');
ob_start();
imagepng($img);
$bin = ob_get_clean();
$b64 = base64_encode($bin);
您也可以通过cURL来实现这一点。你只需要一个图像文件的路径,并将其传递给下面给出的函数…
public static function getImageDataFromUrl($url)
{
$urlParts = pathinfo($url);
$extension = $urlParts['extension'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
return $base64;
}
我认为应该是:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- 点击下载Href图片链接
- PHP中的echo, print和print_r有什么区别?
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- Base64长度计算?
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 用背景图像填充SVG路径元素
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']