PHP实现图片等比例缩放与中心不变形裁剪

Miles
Miles
发布时间:2026-10-13| 5人浏览过
原创

本文详细介绍如何使用PHP的GD库实现图片的等比例缩放和中心不变形裁剪。通过计算图像宽高比,自动确定裁剪区域并填充,或按比例缩小尺寸,同时支持JPG、PNG和GIF格式,确保生成高质量的目标图像而不变形或失真。

准备环境与原理分析

在PHP中操作图像通常依赖GD库。无论是缩放还是裁剪,核心逻辑都涉及读取原图信息(分辨率、MIME类型),创建目标画布,进行像素级别的复制或重采样(imagecopyresampled),最后输出或保存结果。

第1步:等比例缩放图片

目的:将图片按照指定的比例(如0.6代表缩小为原尺寸的60%)进行缩小,保持长宽比不变。

  • 参数说明: $filename 为目标文件路径;$zoom 为缩放比例系数(浮点数),默认为 0.6。
  • 操作:首先获取原图的宽、高及MIME类型;根据缩放比例计算新的宽和高($targetWidth = $sourceWidth * $targetRatio)。然后创建一个临时中间画布与原图等大,将原图拷贝到该画布上以避免内存错误;接着使用 imagecopyresampled 将临时画布的内容缩放到最终的目标画布中;最后设置头部信息输出 JPG 格式图像并销毁所有资源对象。
<?php
/**
 * imageZoom - PHP等比例缩放图片
 * @param string $filename 源图片路径
 * @param double $zoom 缩放比例,默认0.6
 */
function imageZoom($filename,$zoom=0.6){
  // 1. 获取原图基本信息
  $sourceImageInfo = getimagesize($filename);
  $sourceWidth = $sourceImageInfo[0];
  $sourceHeight = $sourceImageInfo[1];
  $sourceMine = $sourceImageInfo['mime'];
  
  // 2. 计算目标尺寸
  $targetRatio = $zoom;
  $targetWidth = $sourceWidth*$targetRatio;
  $targetHeight = $sourceHeight*$targetRatio;
  
  // 3. 加载源图像,兼容常见格式
  $sourceImage = null;
  switch($sourceMine){
    case 'image/gif':
      $sourceImage = imagecreatefromgif($filename);
      break;
    case 'image/jpeg':
      $sourceImage = imagecreatefromjpeg($filename);
      break;
    case 'image/png':
      $sourceImage = imagecreatefrompng($filename);
      break;
    default:
      return ; // 不支持的格式直接返回
      break;
  }
  if (!$sourceImage) return;

  // 4. 创建临时画布和目标画布
  // 注意:这里先用临时画布接收原图是为了某些特定情况下的安全拷贝,实际也可直接在resize时指定
  $tempSourceImage = imagecreatetruecolor($sourceWidth, $sourceHeight);
  $targetImage = imagecreatetruecolor($targetWidth,$targetHeight);
  
  // 5. 图像复制与重采样缩放
  imagecopy($tempSourceImage, $sourceImage, 0, 0, 0, 0, $sourceWidth, $sourceHeight);
  imagecopyresampled($targetImage, $tempSourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
  
  // 6. 输出图像
  header('Content-Type: image/jpeg');
  imagejpeg($targetImage);
  
  // 7. 清理内存
  imagedestroy($tempSourceImage);
  imagedestroy($sourceImage);
  imagedestroy($targetImage);
}

// 调用示例
// $filename = "8fcb7a0831b79c61.jpg";
// imageZoom($filename);
?>

第2步:图片不变形裁剪(居中裁剪)

目的:强制将图片裁剪为特定的固定宽度 ($target_width) 和高度 ($target_height),无论原图比例如何,均保证画面不失真、不拉伸,并从中心开始裁剪。

  • 参数说明: $source_path 为原图路径;$target_width 和 $target_height 为目标输出的固定宽高(例如200x200的方形图)。
  • 操作:比较原图宽高比与目标宽高比。若原图更“瘦高”(原图比例 > 目标比例),则以原图全宽为基础,按目标比例裁剪高度;若原图更“宽胖”,则以原图全高为基础,按目标比例裁剪宽度。计算出裁剪区域的起始坐标 ($source_x, $source_y) 和尺寸,利用 imagecopyresampled 一次性完成从原图截取并缩放到最终尺寸的操作。
<?php
/**
 * imageCropper - PHP不变形居中裁剪图片
 * @param string $source_path 源图片路径
 * @param int $target_width 目标宽度
 * @param int $target_height 目标高度
 */
function imageCropper($source_path, $target_width, $target_height){
  // 1. 获取源图像信息
  $source_info = getimagesize($source_path);
  $source_width = $source_info[0];
  $source_height = $source_info[1];
  $source_mime = $source_info['mime'];
  
  // 2. 计算比例并进行判断
  $source_ratio = $source_height / $source_width;
  $target_ratio = $target_height / $target_width;
  
  $cropped_width = 0;
  $cropped_height = 0;
  $source_x = 0;
  $source_y = 0;

  if ($source_ratio > $target_ratio){
    // 原图较瘦高:以宽度为基准,裁剪多余的高度
    $cropped_width = $source_width;
    $cropped_height = $source_width * $target_ratio;
    $source_x = 0;
    $source_y = ($source_height - $cropped_height) / 2; // 垂直居中
  } elseif ($source_ratio < $target_ratio){
    // 原图较宽胖:以高度为基准,裁剪多余的宽度
    $cropped_width = $source_height / $target_ratio;
    $cropped_height = $source_height;
    $source_x = ($source_width - $cropped_width) / 2; // 水平居中
    $source_y = 0;
  } else {
    // 比例一致,无需额外偏移,直接全量取用(但后续仍需缩放)
    $cropped_width = $source_width;
    $cropped_height = $source_height;
    $source_x = 0;
    $source_y = 0;
  }

  // 3. 加载源图像
  $source_image = null;
  switch ($source_mime){
    case 'image/gif':
      $source_image = imagecreatefromgif($source_path);
      break;
    case 'image/jpeg':
      $source_image = imagecreatefromjpeg($source_path);
      break;
    case 'image/png':
      $source_image = imagecreatefrompng($source_path);
      break;
    default:
      return ;
      break;
  }
  if (!$source_image) return;

  // 4. 创建目标图像和中间裁剪图像
  $target_image = imagecreatetruecolor($target_width, $target_height);
  $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
  
  // 5. 先复制到中间画布(实际这一步可以省略,直接在下面的resampled中指定源坐标即可,但为了代码逻辑清晰保留了步骤)
  imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
  
  // 6. 缩放至最终目标尺寸
  imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
  
  // 7. 输出
  header('Content-Type: image/jpeg');
  imagejpeg($target_image);
  
  // 8. 清理
  imagedestroy($source_image);
  imagedestroy($target_image);
  imagedestroy($cropped_image);
}

// 调用示例
// $filename = "8fcb7a0831b79c61.jpg";
// imageCropper($filename, 200, 200); // 裁剪为200x200的正方形
?>

以上就是PHP实现图片等比例缩放与不变形裁剪的详细代码教程。在实际项目中,建议根据需求选择保存本地文件或浏览器直接输出。更多关于PHP图像处理的技术资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。