Php 从其他URL获取图像时,将图像转换为base64
我正在使用php代码从其他URL获取图像和数据 但需要将图像转换为base64字符串。。!! 代码是Php 从其他URL获取图像时,将图像转换为base64,php,image,base64,Php,Image,Base64,我正在使用php代码从其他URL获取图像和数据 但需要将图像转换为base64字符串。。!! 代码是 <?php function getMetaTitle($content){ $pattern = "|<[\s]*title[\s]*>([^<]+)<[\s]*/[\s]*title[\s]*>|Ui"; if(preg_match($pattern, $content, $match)) return $match[1]; else
<?php
function getMetaTitle($content){
$pattern = "|<[\s]*title[\s]*>([^<]+)<[\s]*/[\s]*title[\s]*>|Ui";
if(preg_match($pattern, $content, $match))
return $match[1];
else
return false;
}
function fetch_record($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("Problem occured");
}
$data = '';
while (!feof($file))
{
$data .= fgets($file, 1024);
}
return $data;
}
$url = $_POST['url'];
$data = array();
// get url title
$content = @file_get_contents($url);
$data['title'] = getMetaTitle($content);
// get url description from meta tag
$tags = @get_meta_tags($url);
$data['description'] = $tags['description'];
$string = fetch_record($url);
// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $content, $img, PREG_PATTERN_ORDER);
$images_array = $img[1];
$k=1;
for ($i=0;$i<=sizeof($images_array);$i++)
{
if(@$images_array[$i])
{
if(@getimagesize(@$images_array[$i]))
{
list($width, $height, $type, $attr) = getimagesize(@$images_array[$i]);
if($width > 50 && $height > 50 ){
$data['images'] = "<img src='".@$images_array[$i]."' id='".$k."' width='100%'>";
$k++;
}
}
}
}
$data['form'] = '<input type="hidden" name="images" value="'.$data['images'].'"/>
<input type="hidden" name="title" value="'.$data['title'].'"/>
<input type="hidden" name="description" value="'.$data['description'].'"/>';
$dom = new domDocument;
@$dom->loadHTML($content);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach($images as $img)
{
$url = $img->getAttribute('src');
$alt = $img->getAttribute('alt');
$pos = strpos($url, 'http://');
if ($pos === false) {
// $data['images'] = '<img src="'.$_POST['url'].''.$url.'" title="'.$alt.'"/>';
} else {
// $data['images'] = '<img src="'.$url.'" title="'.$alt.'"/>';
}
}
echo json_encode($data);
?>
一旦你有了图像的url,你只需要用curl抓取它并调用base64_encode。
分块只会让事情变得更糟
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$ret_val = curl_exec($curl);
// TODO: error checking!!!
$b64_image_data = chunk_split(base64_encode($ret_val));
curl_close($curl);
另一个选项是让PHP使用流转换过滤器()将图像的二进制数据过滤成Base64编码值
我试过这个。。!!但是它不能正常工作。。!!我不知道我哪里错了@基本桥接:我不确定,但你们不获取图像,只获取页面本身。在执行任何其他操作之前,请使用file\u get\u contents()
获取图像。你要做的就是检查图片URL中的宽度、高度和其他垃圾(没有意义)。
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true );
$ret_val = curl_exec($curl);
// TODO: error checking!!!
$b64_image_data = chunk_split(base64_encode($ret_val));
curl_close($curl);
$img_url = 'http://www.php.net/images/php.gif';
$b64_url = 'php://filter/read=convert.base64-encode/resource='.$img_url;
$b64_img = file_get_contents($b64_url);
echo $b64_img;