根据文字改变图片尺寸的PHP代码
以下是一个使用PHP实现根据输入的文字动态调整图片尺寸的示例代码。该代码使用GD库来处理图片。
1. 创建HTML表单
首先,我们需要一个HTML表单来接受用户输入的文字和新的图片尺寸。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片尺寸调整</title>
</head>
<body>
    <form action="resize_image.php" method="post">
        <label for="width">宽度:</label>
        <input type="number" name="width" id="width" required>
        <br>
        <label for="height">高度:</label>
        <input type="number" name="height" id="height" required>
        <br>
        <label for="text">输入文字:</label>
        <input type="text" name="text" id="text" required>
        <br>
        <button type="submit">调整图片尺寸</button>
    </form>
</body>
</html>
2. PHP处理脚本(resize_image.php)
这个PHP脚本将处理表单提交的数据,并根据输入的文字调整图片尺寸。
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取用户输入的数据
    $width = intval($_POST['width']);
    $height = intval($_POST['height']);
    $text = $_POST['text'];
    // 检查输入数据的有效性
    if ($width > 0 && $height > 0 && !empty($text)) {
        // 加载原始图片
        $imagePath = 'path_to_your_image.jpg'; // 替换为你的图片路径
        $image = imagecreatefromjpeg($imagePath);
        if ($image) {
            // 创建新的图像资源
            $newImage = imagecreatetruecolor($width, $height);
            // 调整图片尺寸
            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));
            // 设置字体和颜色
            $font = __DIR__ . '/path_to_your_font.ttf'; // 替换为你的字体文件路径
            $fontSize = 20;
            $color = imagecolorallocate($newImage, 255, 255, 255); // 白色文字
            // 在图片上添加文字
            imagettftext($newImage, $fontSize, 0, 10, 30, $color, $font, $text);
            // 输出并保存新的图片
            header('Content-Type: image/jpeg');
            imagejpeg($newImage);
            imagedestroy($newImage);
        } else {
            echo '无法加载原始图片';
        }
    } else {
        echo '输入数据无效';
    }
} else {
    echo '无效的请求方法';
}
?>
说明
- HTML表单:提供用户输入图片的新宽度、高度和文字。
- PHP处理脚本: 
  - 接收并验证用户输入的数据。
- 加载原始图片。
- 创建一个新的图像资源,并调整大小。
- 使用指定的字体和颜色在图片上添加文字。
- 输出并保存新的图片。
 










