我正在使用 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
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);
?>
此代码在该行使用标准扩展中的图像
$data['images'] = "<img src='".@$images_array[$i]."' id='".$k."' width='100%'>";
我想将它们转换为 base64 并使用
最佳答案
一旦你有了图像的 url,你只需要用 curl 抓取它并调用 base64_encode。 chunk_split 只是让它变得完美。
$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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7214702/