現在の位置: ホーム> 最新記事一覧> 透明な影でテキスト画像を作成します

透明な影でテキスト画像を作成します

M66 2025-05-18

Web開発では、ボタン、タイトル、または透かしの美しい影の効果を備えたテキスト画像を動的に生成したい場合があります。幸いなことに、PHPのGDライブラリは強力な画像処理機能を提供します。ここでは、ImageColorallocatealpha()関数が透明性のある色を定義するのに役立ち、透明な影でテキストを簡単に描画できます。

この記事では、ImageColorallocatealpha()関数を使用して透明なシャドウ効果を備えたテキスト画像を作成する方法を段階的に説明します。

ステップ1:キャンバスを作成します

まず、画像キャンバスを作成する必要があります。ここでは、ImageCreateTrueColor()関数を使用して、真の色の画像を作成します。

 <?php
// 広く作成します 400px,高い 100px キャンバス
$width = 400;
$height = 100;
$image = imagecreatetruecolor($width, $height);

// 背景色を設定します(白)
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);

ステップ2:透明チャネルを有効にします

PNG画像の透明な部分を正しく表示するには、ブレンドモードをオフにし、保存アルファチャネルを有効にする必要があります。

 // 混合モードをオフにします
imagealphablending($image, false);
// 有効にする alpha 保存
imagesavealpha($image, true);

ステップ3:透明性で影の色を定義します

ImageColorallocatealpha()関数のパラメーターは(画像、赤、緑、青、アルファ)であり、アルファ値は0(完全に不透明)から127(完全に透明)の範囲です。

たとえば、黒い半透明の影を定義します。

 // 黒い半透明の影を定義します
$shadow_color = imagecolorallocatealpha($image, 0, 0, 0, 60);

注: 60ここでは、半透明効果について意味があります。

ステップ4:影とテキストを描きます

imagettftext()関数を使用してテキストを描画し、フォントファイルパスを指定する必要があります。

 // フォントファイルパス(実際の状況に従って調整してください)
$font = __DIR__ . '/arial.ttf';
$text = 'Hello, m66.net!';
$font_size = 24;

// 影を描きます(数ピクセルがわずかにオフセット)
imagettftext($image, $font_size, 0, 22, 62, $shadow_color, $font, $text);

// メインテキストを描きます(黒)
$text_color = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, $font_size, 0, 20, 60, $text_color, $font, $text);

ステップ5:画像を出力し、メモリをきれいにします

最後に、画像をPNG形式に出力し、リソースを解放します。

 // 設定 header
header('Content-Type: image/png');
// 出力画像
imagepng($image);
// 無料のメモリ
imagedestroy($image);
?>

完全なサンプルコード

<?php
$width = 400;
$height = 100;
$image = imagecreatetruecolor($width, $height);

$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);

imagealphablending($image, false);
imagesavealpha($image, true);

$shadow_color = imagecolorallocatealpha($image, 0, 0, 0, 60);
$text_color = imagecolorallocate($image, 0, 0, 0);

$font = __DIR__ . '/arial.ttf';
$text = 'Hello, m66.net!';
$font_size = 24;

imagettftext($image, $font_size, 0, 22, 62, $shadow_color, $font, $text);
imagettftext($image, $font_size, 0, 20, 60, $text_color, $font, $text);

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>

注意すべきこと

  1. フォントファイル<br> 上記のコードは、 arial.ttfフォントファイルを使用します。スクリプトが配置されているディレクトリにフォントファイルが存在するか、サーバー上の別のフォントパスに変更されていることを確認してください。

  2. 透明性調整
    アルファパラメーターは、必要に応じて調整できます。より透明になりたい場合は、より大きな値(ほぼ127)を使用できます。もっと不透明になりたい場合は、より小さな値を使用できます。

  3. 展開の提案<br> 展開するときは、サーバーのPHP構成でGDライブラリが有効になっていることを確認してください。そうしないと、コードが実行されません。