图片上传

1. 准备工作

2. 创建HTML表单

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="image" />
  <input type="submit" value="上传" />
</form>

3. PHP脚本处理

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (isset($_FILES["image"])) {
    $image = $_FILES["image"];
    $upload_dir = "uploads/";
    $filename = basename($image["name"]);
    $filetemp = $image["tmp_name"];
    $filetype = $image["type"];
    $filesize = $image["size"];

    $allowed = array("jpg", "jpeg", "png", "gif");
    $ext = strtolower(end(explode('.', $filename)));
    if (in_array($ext, $allowed)) {
      if ($filesize < 2000000) {
        if (move_uploaded_file($filetemp, $upload_dir . $filename)) {
          echo "文件上传成功: " . $filename;
        } else {
          echo "文件上传失败";
        }
      } else {
        echo "文件大小超过2MB";
      }
    } else {
      echo "不支持的文件格式";
    }
  }
}
?>

4. 保存上传的图片

图片截取

1. 使用GD库

确保你的PHP安装了GD库。

2. 截取图片

<?php
$image = imagecreatefromjpeg("uploads/image.jpg");
$x = 50; // 截取的起始X坐标
$y = 50; // 截取的起始Y坐标
$width = 100; // 截取的宽度
$height = 100; // 截取的高度

$cut_image = imagecrop($image, ['x' => $x, 'y' => $y, 'width' => $width, 'height' => $height]);

imagejpeg($cut_image, "uploads/cut_image.jpg");
?>

3. 保存截取的图片

总结