1 回答

TA貢獻1811條經驗 獲得超4個贊
我找到了一個不涉及使用 ampify_img 函數而只涉及放大器本身的解決方案,改變了布局。對于那些曾經有同樣困難的人來說,必須實現放大器將他們的<img>標簽圖像<amp-img>即時轉換為標簽,這是一個解決方案,但圖像布局是固定的,保留了縱橫比。.
我也不知道檢查長內容中的每個圖像大小并寫入標簽會消耗多少 cpu 和 ram。但我認為這將是理想的選擇,為每個圖像編寫特定的寬度和高度,而不是分配固定的布局。
解決方案實施起來非常簡單:
function img_to_amp ($html) {
preg_match_all("#<img(.*?)\\/?>#", $html, $matches);
foreach ($matches[1] as $key => $m) {
preg_match_all('/(alt|src|width|height)=("[^"]*")/i', $m, $matches2);
$amp_tag = '<div class="fixed-height-container"><amp-img ';
foreach ($matches2[1] as $key2 => $val) {
$amp_tag .= $val .'='. $matches2[2][$key2] .' ';
}
$amp_tag .= 'class="contain" layout="fill"';
$amp_tag .= '>';
$amp_tag .= '</amp-img></div>';
$html = str_replace($matches[0][$key], $amp_tag, $html);
}
return $html;
}
只需要放: <div class="fixed-height-container">之前<amp-img
并更改:$amp_tag .= 'layout="responsive"'; 到:$amp_tag .= 'class="contain" layout="fill"';
和</div>最后一個結束$amp_tag .= '</amp-img></div>';
您可以在我找到此解決方案的地方查看 amp 教程: amp.dev 站點
這樣你就不需要沿著圖像標簽提供寬度和高度模式。
更新:ampify_img 的作者返回了我的電子郵件,所以這里有一個更好的方法。PHP 從那里檢查 img src 和 getimagesize()。通過這種方式,圖像變得具有響應性。
function img_to_amp ($html) {
preg_match_all("#<img(.*?)\\/?>#", $html, $img_matches);
foreach ($img_matches[1] as $key => $img_tag) {
preg_match_all('/(alt|src|width|height)=["\'](.*?)["\']/i', $img_tag, $attribute_matches);
$attributes = array_combine($attribute_matches[1], $attribute_matches[2]);
if (!array_key_exists('width', $attributes) || !array_key_exists('height', $attributes)) {
if (array_key_exists('src', $attributes)) {
list($width, $height) = getimagesize($attributes['src']);
$attributes['width'] = $width;
$attributes['height'] = $height;
}
}
$amp_tag = '<amp-img ';
foreach ($attributes as $attribute => $val) {
$amp_tag .= $attribute .'="'. $val .'" ';
}
$amp_tag .= 'layout="responsive"';
$amp_tag .= '>';
$amp_tag .= '</amp-img>';
$html = str_replace($img_matches[0][$key], $amp_tag, $html);
}
return $html;
}
您還可以檢查代碼并在https://gist.github.com/elalemanyo/034490164beb7b935559585ff1cc7d9f 上做出貢獻
- 1 回答
- 0 關注
- 181 瀏覽
添加回答
舉報