PHP使用GD函数库剪裁图片+保存本地

本文介绍了一种使用PHP实现的图片剪裁方法,通过自定义函数实现从指定位置开始的图片区域裁剪,并保存为新的文件。该方法适用于多种图片格式,包括JPEG、PNG、GIF等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
	//剪裁图片
	//1,打开图像
	//2,创建一个空白的图像
	$name="./img/1.jpg";
	 // cut($name,0,0,200,200);
	$x1=289;
	$y1=149;
	$x2=438;
	$y2=257;
	cut($name,289,149,438,257);
	 function cut($name,$x1,$y1,$x2,$y2){
			function getinfo($name){
				
				//getimagesize($dname)函数可以动态的获取图片类型,大小,宽度和高度等
				$info=getimagesize($name);
				$width=$info[0];
				$height=$info[1];
				$mime=$info['mime'];

				switch ($mime) {
					case 'image/jpeg':
					$res=imagecreatefromjpeg($name);
					break;
					case 'image/gif':
					$res=imagecreatefromgif($name);
					break;
					case 'image/png':
					$res=imagecreatefrompng($name);
					break;
					case 'image/wbmp':
					$res=imagecreatefromwbmp($name);
					break;
				}
				return array('width'=>$width,'height'=>$height,'res'=>$res);
			}
			$info=getinfo($name);

			$img=imagecreatetruecolor(($x2-$x1),($y2-$y1));
			imagecopymerge($img,$info['res'],0,0,$x1,$y1,($x2-$x1),($y2-$y1),100);
			// header("content-type:image/png");
			// imagepng($img);
			$ext=pathinfo($name,PATHINFO_EXTENSION);
			$rand_name=md5(mt_rand().time()).".".$ext;
			switch($ext){
				case 'jpg':
				case 'jpeg':
				case 'jpe':
					imagejpeg($img,$rand_name);
					break;
				case 'png':
					imagepng($img,$rand_name);
					break;
				case 'gif':
					imagegif($img,$rand_name);
					break;
				case 'bmp':
				case 'wbmp':
					imagewbmp($img,$rand_name);
					break;
			}
			//销毁资源
			imagedestroy($info['res']);
			imagedestroy($img);
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值