PHP随机形状生成器:生成并保存随机颜色和形状的图像

本文介绍了如何使用PHP代码创建一个动态脚本,生成具有随机背景、形状(矩形或椭圆)和颜色的图片,最后以PNG格式保存。
摘要由CSDN通过智能技术生成

<?php
// 创建画布
$imageWidth = 400;
$imageHeight = 400;
$image = imagecreatetruecolor($imageWidth, $imageHeight);

// 创建随机背景颜色
$bgColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagefill($image, 0, 0, $bgColor);

// 创建随机形状和颜色
$shapeTypes = ['rectangle', 'ellipse'];
$shapeType = $shapeTypes[array_rand($shapeTypes)];
$shapeColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));

// 在画布上绘制形状
if ($shapeType === 'rectangle') {
    $x1 = rand(0, $imageWidth / 2);
    $y1 = rand(0, $imageHeight / 2);
    $x2 = rand($imageWidth / 2, $imageWidth);
    $y2 = rand($imageHeight / 2, $imageHeight);
    imagefilledrectangle($image, $x1, $y1, $x2, $y2, $shapeColor);
} else {
    $cx = rand(0, $imageWidth);
    $cy = rand(0, $imageHeight);
    $width = rand(50, 150);
    $height = rand(50, 150);
    imagefilledellipse($image, $cx, $cy, $width, $height, $shapeColor);
}

// 生成 PNG 图像并保存
$imageFileName = 'random_shape.png';
imagepng($image, $imageFileName);

// 销毁画布资源
imagedestroy($image);

echo "随机形状已生成并保存为 $imageFileName 文件。";
?>
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值