[php] jpeg画像に文字を追加する imagettftext

jpeg画像に文字を追加するには以下のコードを実装する

下のコードでは、imagettfbboxで追加されたテキスト全体の位置情報を取得し、その後でテキストを縦横中央に配置している。

 

 $jpg = "元画像のパス";

 // 色を設定
 $white = imagecolorallocate($jpg, 255, 255, 255);
 $grey = imagecolorallocate($jpg, 128, 128, 128);
 $black = imagecolorallocate($jpg, 0, 0, 0);

 $media= "出力画像のパス";
 $font = '/usr/share/fonts/truetype/vlgothic/VL-Gothic-Regular.ttf'; //fontのパス

 $fontsize = 20;
 
 $str = "ああああああ";
 $text = '';
 $text .= mb_convert_encoding($str, 'UTF-8',auto);
 $text .= "\n"; //改行
 $text .= mb_convert_encoding($str, 'UTF-8',auto);
 
 $image = imagecreatefromjpeg($jpg);
 
 $result = imagettfbbox($fontsize, 0, $font, $text); //テキスト全体の位置情報取得
 // 左上
 $x0 = $result[6];
 $y0 = $result[7];
 // 右下
 $x1 = $result[2];
 $y1 = $result[3];
 $width = $x1 - $x0;
 $height = $y1 - $y0;
 $x = ceil((500 - $width) / 2); //500は画像の幅
 $y = ceil((200 - $height) / 2); //200は画像の縦
 
 
 // テキストを追加
 imagettftext($image, $fontsize, 0, $x, $y, $black, $font, $text);
 
 imagejpeg($image, $media);
 imagedestroy($image);
 echo "<img src= " . $media . ">";

 

いろいろつまづいたところ:

目次

改行\nが入らない

改行\nが入らない場合は、”\n”とダブルクオーテーションで囲む必要がある

 

文字化けする

挿入した文字が文字化けする場合はUTF-8である必要があるため、UTF-8に文字を変換する

 $text .= mb_convert_encoding($str, 'UTF-8',auto);

そもそも画像が生成されない

画像が生成されない場合は、生成する先の場所に書き込み権限があるか確認する

 

文字が入らない

画像に文字が入らない場合は、指定しているフォントが存在するか、指定しているフォントのパスが正しいかを確認。

 

 

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です