如何用php写一个生日蛋糕
时间: 2024-06-12 22:04:25 浏览: 14
以下是一个简单的PHP生日蛋糕示例代码:
```php
<?php
// 设置画布大小
$width = 500;
$height = 500;
// 创建画布
$image = imagecreatetruecolor($width, $height);
// 设置颜色
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
$cake_color = imagecolorallocate($image, 255, 165, 0);
$candle_color = imagecolorallocate($image, 255, 0, 0);
// 填充背景色
imagefill($image, 0, 0, $background_color);
// 绘制蛋糕
$radius = 150; // 蛋糕半径
$x = $width / 2; // 蛋糕中心点x坐标
$y = $height / 2; // 蛋糕中心点y坐标
imagefilledellipse($image, $x, $y, $radius * 2, $radius, $cake_color);
// 绘制蜡烛
$num_candles = 5; // 蜡烛数量
$candle_radius = 10; // 蜡烛半径
$candle_gap = 30; // 蜡烛间隔
$candle_y = $y - $radius - $candle_radius; // 蜡烛y坐标
for ($i = 0; $i < $num_candles; $i++) {
$candle_x = $x - ($num_candles - 1) / 2 * $candle_gap + $i * $candle_gap; // 蜡烛x坐标
imagefilledellipse($image, $candle_x, $candle_y, $candle_radius * 2, $candle_radius * 2, $candle_color);
}
// 添加生日祝福语
$text = "Happy Birthday!";
$font_size = 30;
$font_file = "arial.ttf";
$text_width = imagettfbbox($font_size, 0, $font_file, $text)[2] - imagettfbbox($font_size, 0, $font_file, $text)[0];
$text_x = $x - $text_width / 2;
$text_y = $y + $radius + $font_size * 1.5;
imagettftext($image, $font_size, 0, $text_x, $text_y, $text_color, $font_file, $text);
// 输出图片
header('Content-type: image/png');
imagepng($image);
// 释放内存
imagedestroy($image);
?>
```
该代码使用PHP的GD库绘制生日蛋糕图像,通过设置画布大小、颜色、绘制蛋糕和蜡烛、添加生日祝福语等步骤来实现。最终将图像输出给浏览器显示。