当前位置: 首页 > 编程文章 >

PHP图像裁剪与缩略图生成类实现详解

PHP图像裁剪与缩略图生成类实现详解

作者:顾澄时间:2025-02-18 13:12:19浏览:106

针对网页拖拽验证码项目中服务端生成可移动色块的需求,本文介绍一个自定义的PHP图像裁剪与缩略图生成类。该类基于GD库核心函数imagecopy和imagecopyresampled实现,支持对原图指定区域进行精确裁剪及整体缩放处理。通过实例代码展示如何实例化对象、设置裁剪参数并保存结果,解决现有资源仅支持全图缩放的局限。

本文目录展开

背景与需求分析

近期在开发一款开源的网页拖拽验证码项目时,面临一个技术难点:需要在服务器端从原始图片中提取出可移动的彩色方块。然而,市面上现有的解决方案大多仅支持对整个图像进行等比例缩放以生成缩略图,无法满足局部提取的需求。为此,开发者自行编写了一套专门用于从图片中裁剪小块区域的工具类。


<?php
namespace App\Libs;
/**
* 2016-01-07 15:54:58
* Lixiaoyu
* 
* mode 1 : 强制裁剪,生成图片严格按照需要,不足放大,超过裁剪,图片始终铺满
* mode 2 : 和1类似,但不足的时候 不放大 会产生补白,可以用png消除。
* mode 3 : 只缩放,不裁剪,保留全部图片信息,会产生补白,
* mode 4 : 只缩放,不裁剪,保留全部图片信息,生成图片大小为最终缩放后的图片有效信息的实际大小,不产生补白
* 默认补白为白色,如果要使补白成透明像素,请使用SaveAlpha()方法代替SaveImage()方法
*/
class ImageCrop{
var $sImage;
var $dImage;
var $src_file;
var $dst_file;
var $src_width;
var $src_height;
var $src_ext;
var $src_type;
function __construct($src_file,$dst_file=''){
$this->src_file=$src_file;
$this->dst_file=$dst_file;
$this->LoadImage();
}
function SetSrcFile($src_file){
$this->src_file=$src_file;
}
function SetDstFile($dst_file){
$this->dst_file=$dst_file;
}
function LoadImage(){
list($this->src_width, $this->src_height, $this->src_type) = getimagesize($this->src_file);
switch($this->src_type) {
case IMAGETYPE_JPEG :
$this->sImage=imagecreatefromjpeg($this->src_file);
$this->ext='jpg';
break;
case IMAGETYPE_PNG :
$this->sImage=imagecreatefrompng($this->src_file);
$this->ext='png';
break;
case IMAGETYPE_GIF :
$this->sImage=imagecreatefromgif($this->src_file);
$this->ext='gif';
break;
default:
exit();
}
}
function SaveImage($fileName=''){
$this->dst_file=$fileName ? $fileName : $this->dst_file;
switch($this->src_type) {
case IMAGETYPE_JPEG :
imagejpeg($this->dImage,$this->dst_file,100);
break;
case IMAGETYPE_PNG :
imagepng($this->dImage,$this->dst_file);
break;
case IMAGETYPE_GIF :
imagegif($this->dImage,$this->dst_file);
break;
default:
break;
}
}
function OutImage(){
switch($this->src_type) {
case IMAGETYPE_JPEG :
header('Content-type: image/jpeg');
imagejpeg($this->dImage);
break;
case IMAGETYPE_PNG :
header('Content-type: image/png');
imagepng($this->dImage);
break;
case IMAGETYPE_GIF :
header('Content-type: image/gif');
imagegif($this->dImage);
break;
default:
break;
}
}
function SaveAlpha($fileName=''){
$this->dst_file=$fileName ? $fileName . '.png' : $this->dst_file .'.png';
imagesavealpha($this->dImage, true);
imagepng($this->dImage,$this->dst_file);
}
function OutAlpha(){
imagesavealpha($this->dImage, true);
header('Content-type: image/png');
imagepng($this->dImage);
}
function destory(){
imagedestroy($this->sImage);
imagedestroy($this->dImage);
}
function Crop($dst_width,$dst_height,$mode=1,$dst_file=''){
if($dst_file) $this->dst_file=$dst_file;
$this->dImage = imagecreatetruecolor($dst_width,$dst_height);
$bg = imagecolorallocatealpha($this->dImage,255,255,255,127);
imagefill($this->dImage, 0, 0, $bg);
imagecolortransparent($this->dImage,$bg);
$ratio_w=1.0 * $dst_width / $this->src_width;
$ratio_h=1.0 * $dst_height / $this->src_height;
$ratio=1.0;
switch($mode){
case 1: // always crop
if( ($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)){
$ratio = $ratio_w < $ratio_h ? $ratio_h : $ratio_w;
$tmp_w = (int)($dst_width / $ratio);
$tmp_h = (int)($dst_height / $ratio);
$tmp_img=imagecreatetruecolor($tmp_w , $tmp_h);
$src_x = (int) (($this->src_width-$tmp_w)/2) ;
$src_y = (int) (($this->src_height-$tmp_h)/2) ;
imagecopy($tmp_img, $this->sImage, 0,0,$src_x,$src_y,$tmp_w,$tmp_h);
imagecopyresampled($this->dImage,$tmp_img,0,0,0,0,$dst_width,$dst_height,$tmp_w,$tmp_h);
imagedestroy($tmp_img);
}else{
$ratio = $ratio_w < $ratio_h ? $ratio_h : $ratio_w;
$tmp_w = (int)($this->src_width * $ratio);
$tmp_h = (int)($this->src_height * $ratio);
$tmp_img=imagecreatetruecolor($tmp_w ,$tmp_h);
imagecopyresampled($tmp_img,$this->sImage,0,0,0,0,$tmp_w,$tmp_h,$this->src_width,$this->src_height);
$src_x = (int)($tmp_w - $dst_width) / 2 ;
$src_y = (int)($tmp_h - $dst_height) / 2 ;
imagecopy($this->dImage, $tmp_img, 0,0,$src_x,$src_y,$dst_width,$dst_height);
imagedestroy($tmp_img);
}
break;
case 2: // only small
if($ratio_w < 1 && $ratio_h < 1){
$ratio = $ratio_w < $ratio_h ? $ratio_h : $ratio_w;
$tmp_w = (int)($dst_width / $ratio);
$tmp_h = (int)($dst_height / $ratio);
$tmp_img=imagecreatetruecolor($tmp_w , $tmp_h);
$src_x = (int) ($this->src_width-$tmp_w)/2 ;
$src_y = (int) ($this->src_height-$tmp_h)/2 ;
imagecopy($tmp_img, $this->sImage, 0,0,$src_x,$src_y,$tmp_w,$tmp_h);
imagecopyresampled($this->dImage,$tmp_img,0,0,0,0,$dst_width,$dst_height,$tmp_w,$tmp_h);
imagedestroy($tmp_img);
}elseif($ratio_w > 1 && $ratio_h > 1){
$dst_x = (int) abs($dst_width - $this->src_width) / 2 ;
$dst_y = (int) abs($dst_height -$this->src_height) / 2;
imagecopy($this->dImage, $this->sImage,$dst_x,$dst_y,0,0,$this->src_width,$this->src_height);
}else{
$src_x=0;$dst_x=0;$src_y=0;$dst_y=0;
if(($dst_width - $this->src_width) < 0){
$src_x = (int) ($this->src_width - $dst_width)/2;
$dst_x =0;
}else{
$src_x =0;
$dst_x = (int) ($dst_width - $this->src_width)/2;
}
if( ($dst_height -$this->src_height) < 0){
$src_y = (int) ($this->src_height - $dst_height)/2;
$dst_y = 0;
}else{
$src_y = 0;
$dst_y = (int) ($dst_height - $this->src_height)/2;
}
imagecopy($this->dImage, $this->sImage,$dst_x,$dst_y,$src_x,$src_y,$this->src_width,$this->src_height);
}
break;
case 3: // keep all image size and create need size
if($ratio_w > 1 && $ratio_h > 1){
$dst_x = (int)(abs($dst_width - $this->src_width )/2) ;
$dst_y = (int)(abs($dst_height- $this->src_height)/2) ;
imagecopy($this->dImage, $this->sImage, $dst_x,$dst_y,0,0,$this->src_width,$this->src_height);
}else{
$ratio = $ratio_w > $ratio_h ? $ratio_h : $ratio_w;
$tmp_w = (int)($this->src_width * $ratio);
$tmp_h = (int)($this->src_height * $ratio);
$tmp_img=imagecreatetruecolor($tmp_w ,$tmp_h);
imagecopyresampled($tmp_img,$this->sImage,0,0,0,0,$tmp_w,$tmp_h,$this->src_width,$this->src_height);
$dst_x = (int)(abs($tmp_w -$dst_width )/2) ;
$dst_y = (int)(abs($tmp_h -$dst_height)/2) ;
imagecopy($this->dImage, $tmp_img, $dst_x,$dst_y,0,0,$tmp_w,$tmp_h);
imagedestroy($tmp_img);
}
break;
case 4: // keep all image but create actually size
if($ratio_w > 1 && $ratio_h > 1){
$this->dImage = imagecreatetruecolor($this->src_width,$this->src_height);
imagecopy($this->dImage, $this->sImage,0,0,0,0,$this->src_width,$this->src_height);
}else{
$ratio = $ratio_w > $ratio_h ? $ratio_h : $ratio_w;
$tmp_w = (int)($this->src_width * $ratio);
$tmp_h = (int)($this->src_height * $ratio);
$this->dImage = imagecreatetruecolor($tmp_w ,$tmp_h);
imagecopyresampled($this->dImage,$this->sImage,0,0,0,0,$tmp_w,$tmp_h,$this->src_width,$this->src_height);
}
break;
}
}// end Crop
/**
*
* 裁切方法
* 2026-01-07 15:05:44
* Lixiaoyu
*
* @param $dst_width 目标长
* @param $dst_height 目标高
* @param $dst_x 裁剪部分和原图左侧的距离
* @param $dst_y 裁剪部分和原图右侧的距离
* @param int $mode 模式
* @param string $dst_file 目标文件路径
*/
function Cut($dst_width,$dst_height,$dst_x,$dst_y,$dst_file='')
{
if ($dst_file) $this->dst_file = $dst_file; //设置目标文件位置
$this->dImage = imagecreatetruecolor($dst_width, $dst_height); //创建了目标文件的大小的画布
$bg = imagecolorallocatealpha($this->dImage, 255, 255, 255, 127); //给画布分配颜色
imagefill($this->dImage, 0, 0, $bg); //给图像用颜色进行填充
imagecolortransparent($this->dImage, $bg); //背景定义成透明色
$ratio_w = 1.0 * $dst_width / $this->src_width; //横向缩放的比例
$ratio_h = 1.0 * $dst_height / $this->src_height; //纵向缩放的比例
//var_dump($this);
//不进行缩放,直接对图像进行裁剪
$ratio = 1.0;
$tmp_w = (int)($dst_width / $ratio);
$tmp_h = (int)($dst_height / $ratio);
$tmp_img = imagecreatetruecolor($dst_width, $dst_height); //创建暂时保存的画布
imagecopy($tmp_img, $this->sImage, 0,0,$dst_x,$dst_y,$dst_width,$dst_height); //拷贝出图像的一部分,进行裁切
imagecopyresampled($this->dImage,$tmp_img,0,0,0,0,$dst_width,$dst_height,$tmp_w,$tmp_h); //把暂时缓存的图片,放到目标文件里面
imagedestroy($tmp_img);
}
}
?>

使用方法

裁剪图像


$ic=new ImageCrop($pathToFile,'./pic/afterCrop'.time().'.jpg');
$ic->Cut(40,30,120,130);
$ic->SaveImage();
//$ic->SaveAlpha();将补白变成透明像素保存
$ic->destory();

实现效果

原始图片

原图

裁剪后的图片

裁剪之后的图

缩放图像

原始图片

原图

生成的缩略图

缩略图

本工具类的核心技术基础在于调用PHP的图像处理函数 imagecopy 以及 imagecopyresampled。

bool imagecopy ( resource dstim, resourcesrc_im , int dstx,intdst_y , int srcx,intsrc_y , int srcw,intsrc_h ) 该函数的作用是将源图像 src_im 中,从坐标 (src_x, src_y) 开始,宽度为 src_w,高度为 src_h 的矩形区域,拷贝到目标图像 dst_im 中,放置于坐标 (dst_x, dst_y) 的位置。

上一篇
PHP调试及性能分析工具Xdebug详解

Xdebug是用于跟踪、调试和分析PHP程序运行状况的扩展工具。本文详细讲解了在Windows和Linux平台下的安装配置步骤,包括模块加载、php.ini参数设置及服务重启。通过生成跟踪日志并结合WinCacheGrind等可视化工具,开发者可以直观查看函数调用次数与执行时间,从而快速定位脚本执行和数据库查询的性能瓶颈,提升系统整体效率。

下一篇
PHP纯代码实现定时任务:基于信号与PCNTL扩展的机制解析

本文介绍在Linux环境下使用PHP CLI模式实现纯代码定时任务的方案。通过PCNTL扩展捕获SIGALRM信号,每秒触发回调函数遍历任务队列,支持参数传递及持久化执行,适用于长期运行的服务场景。

相关文章

更多
PHP生成圆角图片的实现方法

本文介绍了一种使用PHP生成圆角图片的具体实现方法。通过调用GD库函数,可以创建具有平滑边缘的图像资源,适用于网页设计中的头像或图标展示。该方法提供了完整的代码示例,帮助开发者快速掌握在PHP环境中处理图像形状的技巧,提升前端视觉体验。

2025.05.03 978
PHP实现自定义图像居中裁剪函数示例

本文介绍了一种基于PHP的自定义图像居中裁剪方法。核心思路是先通过imagecopyresampled将原图缩放至覆盖目标区域,再利用imagecopy截取中间部分,最后保存结果。文中提供了完整函数代码及调用示例,并针对常见的exif_imagetype未定义错误给出了启用扩展和兼容低版本PHP的具体解决方案。

2026.04.30 967
PHP图像处理函数实战:像素级文字着色示例

本文介绍如何利用PHP的图像函数实现像素级文字着色效果。通过结合getimagesize获取图片尺寸、imagecreatefromgif加载GIF资源,以及imagecolorat和imagecolorsforindex读取并转换RGB颜色值,遍历图像像素动态生成带颜色的HTML输出。该示例旨在通过趣味实践激发学习兴趣,适用于小尺寸Logo等轻量级图像的探索性开发。

2026.07.02 963
PHP图像处理示例代码汇总

本文通过六个具体的PHP文件(Demo1.php至Demo6.php)展示了图像处理的常见实现方式。这些示例涵盖了从基础操作到复杂应用的多种场景,旨在为开发者提供实用的参考代码,帮助快速掌握PHP在图形处理方面的编程技巧。

2025.03.11 868
PHP使用GD库创建图像的具体步骤与格式支持

本文详细介绍如何利用PHP结合GD库创建和处理多种格式的图像,包括GIF、PNG、JPEG等。重点讲解在验证码场景下,如何通过编译GD库实现图像数据流直接输出到浏览器,并列出关键函数参考路径,帮助开发者快速掌握PHP绘图基础。

2025.03.16 860
PHP版阿里云OSS图片上传类实现详解

本文详细介绍基于PHP的阿里云OSS图片上传类的实现逻辑。该类通过调用阿里云OSS接口直接保存文件至云端,区别于传统本地服务器上传。核心功能涵盖文件校验、格式检测、缩略图生成及云端存储,支持自定义配置如最大文件大小、允许后缀及缩略图尺寸等参数。

2026.05.13 856

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。