mazeltov7のweb断片

備忘録的なテキトーなことを書きます。(技術記事はQiitaに移行しました http://qiita.com/mazeltov7 )

PHPで画像に文字を載せて、画像を生成する

ユーザーに入れてもらった文字を、画像の上に載せて、画像として吐き出したい、ってことがあったので、その際にやったことをメモ。
イメージは下のやつみたいな感じ。

よくわからんけど、こんな感じの作れる。

f:id:mazeltov7:20140911004825p:plain

以下、ざっくりメモ。
→画像に文字とアイコンを載せて、画像生成。

header("Content-Type: image/jpeg");

$imageframe = imagecreatefromstring(file_get_contents("img/hoge.png")); //載せる画像
$result = imagecreatetruecolor(190, 70); //フィールド作成
$white = imagecolorallocate($result, 255, 255, 255); //白カラー作成
$blue = imagecolorallocate($result, 51,51,255); //青カラー作成

imagefilledrectangle($result, 0, 0, 190, 70, $white);  //デフォ黒のフィールドを白に

imagecopyresampled($result, $frame, 0, 0, 0, 0, 190, 70, 190, 70); //フィールドに画像を載せる

$icon = imagecreatefromstring(file_get_contents("http://hoge.com/img/hogehoge")); //アイコン画像
imagecopyresampled($result, $icon, 8, 48, 0, 0, 19, 19, 48, 48); //画像にアイコン載せる

imagefttext($result, 7, 0, 30, 62, $blue, '/font/HiraginoMaruStdW8.otf', "YO!YO!"); //画像に青文字を載せる

imagepng($result); //pngとして生成

参考はマニュアル。 PHP: imagefttext - Manual