2024/04/16

色々な画像ファイル形式をhtmlに埋め込む(PHP)

画像をhtmlに埋め込む際、単一の場合は img/src、複数の拡張子を指定すると img/source/srcsetに展開してくれる便利関数。また、単一拡張子のみが指定されている場合は、ブラウザのサポート状況に応じ、avifやwebpの拡張子を持つ同名のファイルがある場合は[avif/webp]の優先順位で表示する画像ファイル名(拡張子)を変更するおまけ機能付き。

/*
 * $src: 画像ファイル名。'|' で区切られている拡張子がある場合は source srcset に展開
 *       picture.jpg  => <img src="picture.jpg" />
 *       picture.jpg|avif|webp  => <source></source>
 *                                   <srcset picture.avif="" type="image/avif">
 *                                   <srcset picture.webp="" type="image/webp">
 *                                   <srcset picture.jpg="">
 *                                 
 * 
 *       picture.jpg[2x,3x]  => <source></source>
 * 
 * $width/$height/$alt/$title: 画像幅/画像高さ/alt文字列/title文字列
 * 
 * 
 */

function img($src, $width=null, $height=null, $alt=null, $title=null, $additem=null)
{
	Global $accept_images;

	$w = $width  ? " width=\"{$width}\""   : "";
	$h = $height ? " height=\"{$height}\"" : "";

	// img タグ生成。複数拡張子は pictureタグを生成
	$imgsrc = explode('|', $src);		// 複数拡張子を分解(|があれば)
	$nimgsrc = count($imgsrc);			// 追加拡張子の数(|がなければ 1)
	if ($nimgsrc > 1) {							// 複数拡張子の時の処理
		$src = $imgsrc[0];						// オリジナルの画像ファイル名を保存
		$imgbase = substr($imgsrc[0], 0, strrpos($imgsrc[0], '.'));	// 拡張子を外したファイル名を抽出
		echo "<picture>\n";
		for ($i = 1; $i < $nimgsrc; $i++) {		// 拡張子を変えながら srcsetを作成
			printf("\t<source srcset=\"%s.%s\" type=\"image/%s\" />\n", $imgbase, $imgsrc[$i], $imgsrc[$i]);
		}
		printf("\t<source srcset=\"%s\" />\n", $imgsrc[0]);		// オリジナルの画像を最後に追加
	} elseif ($accept_images) {
		$src = optimalimage($src);
	}

	// img タグの共通部分を表示 (タグはここでは閉じない)
	printf ('<img src="%s"%s%s alt="%s" title="%s" loading="lazy"', $src, $w, $h, $alt, $title);

	if ($additem)	print " {$additem}";

	// img タグの閉じ括弧を表示
	print ' />';
    
	if ($nimgsrc > 1 )	echo "</picture>\n";
}

function optimalimage($src)
{
	Global $accept_images;

	$imgbase = substr($src, 0, strrpos($src, '.'));
	$testuri = ($imgbase[0] == '/' ? $_SERVER['DOCUMENT_ROOT'] : '') . $imgbase;
	if (isset($accept_images['avif']) && file_exists($testuri . '.avif')) {
		$src = $imgbase . '.avif';
	} elseif (isset($accept_images['webp']) && file_exists($testuri . '.webp')) {
		$src = $imgbase . '.webp';
	}

	return $src;
}

/*
 * あらかじめグローバル変数$accept_images(配列)をセットしておく
 */
global $accept_images = null;
$allheaders = getallheaders();
if (isset($allheaders['Accept'])) {
	preg_match_all('|image/([a-z]+)|', $allheaders['Accept'], $matchimages);
	foreach ($matchimages[1] as $imgname) {
		$accept_images["{$imgname}"] = true;
	}
}

0 件のコメント:

色々な画像ファイル形式をhtmlに埋め込む(PHP)

画像をhtmlに埋め込む際、単一の場合は img/src、複数の拡張子を指定すると img/source/srcsetに展開してくれる便利関数。また、単一拡張子のみが指定されている場合は、ブラウザのサポート状況に応じ、avifやwebpの拡張子を持つ同名のファイルがある場合は[a...