3
我正在使用PHP代碼從其他網址獲取圖像和數據 ,但需要將圖像轉換爲base64字符串。 代碼將圖像轉換爲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='"[email protected]$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='"[email protected]$images_array[$i]."' id='".$k."' width='100%'>";
我想將它們轉換爲Base64和他們使用
[base64_encode](http://php.net/base64_encode) – deceze
我試過這個.. !! 但它不能正常工作..! 我不知道我在哪裏錯了..! –
@Basic Bridge:我不確定,但是你不提取圖片,只有頁面本身。在做其他事情之前,使用'file_get_contents()'獲取圖像。你所做的只是檢查圖片URL中的寬度高度和其他垃圾(沒有意義)。 – xfix