我正在尝试编写一种最佳实践的php函数,以将现有的图像标签转换为更丰富的图片元素。请假设我已经转换并保存了所有图像版本。
<?php
//create multi format and resolution picture from img source
function autopicture($imgsrc,$imgclass,$imgalt){
//config
$breakpoint1 = 460;
$breakpoint2 = 1281;
$pathinfo = pathinfo($imgsrc);
$dirname = $pathinfo['dirname'];
$filename = $pathinfo['filename'];
$filetype = $pathinfo['extension'];
$imgsize = getimagesize($imgsrc);
$imgwidth = $imgsize['0'];
$imgheight = $imgsize['1'];
$imgmime = $imgsize['mime'];
$picturecontent='<picture>';
//large
$picturecontent.='<source type="image/webp" media="(min-width: '.($breakpoint2+1).'px)" srcset="../images/uploads/'.$filename.'.webp">';
$picturecontent.='<source type="'.$imgmime.'" media="(min-width: '.($breakpoint2+1).'px)" srcset="../images/uploads/'.$filename.'.'.$filetype.'">';
//medium
$picturecontent.='<source type="image/webp" media="(min-width: '.($breakpoint1+1).'px) and (max-width: '.$breakpoint2.'px)" srcset="../images/uploads/medium/'.$filename.'.webp">';
$picturecontent.='<source type="'.$imgmime.'" media="(min-width: '.($breakpoint1+1).'px) and (max-width: '.$breakpoint2.'px)" srcset="../images/uploads/medium/'.$filename.'.'.$filetype.'">';
//small
$picturecontent.='<source type="image/webp" media="(max-width: '.$breakpoint1.'px)" srcset="../images/uploads/small/'.$filename.'.webp">';
$picturecontent.='<source type="'.$imgmime.'" media="(max-width: '.$breakpoint1.'px)" srcset="../images/uploads/small/'.$filename.'.'.$filetype.'">';
//default to original
$picturecontent.='<img class="'.$imgclass.'" src="../images/uploads/'.$filename.'.'.$filetype.'" width="'.$imgwidth.'" height="'.$imgheight.'" alt="'.$imgalt.'">';
$picturecontent.='</picture>';
return $picturecontent;
}
?>
使用...
<?php echo autopicture("../images/uploads/sample-image.jpg", "imgfill", "sample alt description");?>
我现在的问题是为较小的替代图像固定图像的高度和宽度,而我在这里找不到解决方法。我认为我只能在较早的部分中指定高度和宽度,这是正确的吗?在这种情况下,如何为较小的视口指定分辨率较低的图像的高度和宽度,从而减少“累积布局偏移”的问题?
还-getimagesize()是否会使我慢下来-否定了较低图像加载的好处?