Web開発では、ボタン、タイトル、または透かしの美しい影の効果を備えたテキスト画像を動的に生成したい場合があります。幸いなことに、PHPのGDライブラリは強力な画像処理機能を提供します。ここでは、ImageColorallocatealpha()関数が透明性のある色を定義するのに役立ち、透明な影でテキストを簡単に描画できます。
この記事では、ImageColorallocatealpha()関数を使用して透明なシャドウ効果を備えたテキスト画像を作成する方法を段階的に説明します。
まず、画像キャンバスを作成する必要があります。ここでは、ImageCreateTrueColor()関数を使用して、真の色の画像を作成します。
<?php
// 広く作成します 400px,高い 100px キャンバス
$width = 400;
$height = 100;
$image = imagecreatetruecolor($width, $height);
// 背景色を設定します(白)
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
PNG画像の透明な部分を正しく表示するには、ブレンドモードをオフにし、保存アルファチャネルを有効にする必要があります。
// 混合モードをオフにします
imagealphablending($image, false);
// 有効にする alpha 保存
imagesavealpha($image, true);
ImageColorallocatealpha()関数のパラメーターは(画像、赤、緑、青、アルファ)であり、アルファ値は0(完全に不透明)から127(完全に透明)の範囲です。
たとえば、黒い半透明の影を定義します。
// 黒い半透明の影を定義します
$shadow_color = imagecolorallocatealpha($image, 0, 0, 0, 60);
注: 60ここでは、半透明効果について意味があります。
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);
最後に、画像を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);
?>
フォントファイル<br> 上記のコードは、 arial.ttfフォントファイルを使用します。スクリプトが配置されているディレクトリにフォントファイルが存在するか、サーバー上の別のフォントパスに変更されていることを確認してください。
透明性調整
アルファパラメーターは、必要に応じて調整できます。より透明になりたい場合は、より大きな値(ほぼ127)を使用できます。もっと不透明になりたい場合は、より小さな値を使用できます。
展開の提案<br> 展開するときは、サーバーのPHP構成でGDライブラリが有効になっていることを確認してください。そうしないと、コードが実行されません。