サンプル・プログラムの実行例

サンプル・プログラム
text2image.php | サンプル・プログラム本体 |
解説:画像をHTMLコンテンツに埋め込む
173: /**
174: * 文字列を画像に変換
175: * @param int $mode 0=画面出力,1=画像出力
176: * @param int $font 0|1(フォントの種類)
177: * @param string $str 文字列(UTF-8)
178: * @return string BASE64
179: */
180: function text2image($mode, $font, $str) {
181: //フォント・ファイル
182: static $table = array(
183: '../../../../common/font/mikachan-p.ttf',
184: '../../../../common/font/VL-PGothic-Regular.ttf',
185: '../../../../common/font/nicokaku_v1.ttf',
186: '../../../../common/font/ipamp.ttf'
187: );
188:
189: if ($str == '') return '';
190:
191: $res = '';
192: $size = 20;
193: $arr = imagettfbbox($size, 0, $table[$font], $str); //サイズ取得
194: $im = imagecreate($arr[4] - $arr[6] + 5, $arr[1] - $arr[7] + 5);
195: //イメージストリーム作成
196: $bgcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); //背景色
197: imagecolortransparent($im, $bgcolor); //透明化
198: $color = imagecolorallocate($im, 0x00, 0x00, 0xCC); //文字色
199: imagettftext($im, $size, 0, -$arr[6], -$arr[7], $color, $table[$font], $str); //出力
200:
201: if ($mode == 1) {
202: header("Content-type: image/png"); //MIMEはPNGで
203: imagepng($im); //ブラウザ表示
204: } else {
205: ob_start();
206: imagepng($im); //ブラウザ表示
207: $res = base64_encode(ob_get_clean());
208: }
209: imagedestroy($im); //後処理
210:
211: return $res;
212: }

imgタグの中に画像データを埋め込むには、src属性の中に "data:image/png;base64," の後にBASE64エンコードされた画像データを並べれば良い。
そこで、組み込み関数 ob_start と imagepng を用い出力した画像データを、 ob_get_clean によって取得する。これを base64_encode に渡してやり、src属性の中に並べる。
参考サイト
- PHPでTrueTypeフォントを利用する:ぱふぅ家のホームページ
- PHPセキュリティ対策:メールアドレスを画像表示:ぱふぅ家のホームページ
- オリジナルフォント【みかちゃん】
- VL Gothic Font Family
- dataスキームURI生成
- C#でBase64の文字列にした画像をImageに変換して表示する:Symfoware
- 画像をBase64にしてWebページを高速化:Thought is free
今回は、HTMLコンテンツの中に画像データを埋め込む方法について解説する。この方法を使うことで、1つのPHPプログラムで、テキストと画像を混在するコンテンツを表示することができるようになる。
(2022年4月9日)PHP8対応,リファラ・チェック改良