如何将图像从URL转换为Base64编码?
当前回答
下面是一个使用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);?>">
其他回答
容易:
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);
请记住,这将使数据扩大33%, 如果文件的大小超过了memory_limit,就会出现问题。
我认为应该是:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
您也可以通过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;
}
下面是一个使用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);?>">
也可以用这种方式来表示base64编码格式的图像…
找到PHP函数file_get_content,然后使用函数base64_encode。
并获取结果来准备str作为数据:"。file_mime_type。" Base64_encoded string。在img src属性中使用它。下面的代码可能会有帮助:
// A few settings
$img_file = 'raju.jpg';
// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;
// Echo out a sample image
echo '<img src="'.$src.'">';
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 在Android上调整一个大的位图文件到缩放输出文件
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 使用node.js下载图像
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?