图像居中裁减的大致思路:

1.首先将图像进行缩放,使得缩放后的图像能够恰好覆盖裁减区域。(imagecopyresampled — 重采样拷贝部分图像并调整大小)

2.将缩放后的图像放置在裁减区域中间。(imagecopy — 拷贝图像的一部分)

3.裁减图像并保存。(imagejpeg | imagepng | imagegif — 输出图象到浏览器或文件)

==================缩放裁剪函数====================

/**
* 居中裁剪图片
* @param string $source [原图路径]
* @param int $width [设置宽度]
* @param int $height [设置高度]
* @param string $target [目标路径]
* @return bool [裁剪结果]
*/
function image_center_crop($source, $width, $height, $target)
{
if (!file_exists($source)) return false;
/* 根据类型载入图像 */
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
}
if (!isset($image)) return false;
/* 获取图像尺寸信息 */
$target_w = $width;
$target_h = $height;
$source_w = imagesx($image);
$source_h = imagesy($image);
/* 计算裁剪宽度和高度 */
$judge = (($source_w / $source_h) > ($target_w / $target_h));
$resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
$resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
$start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
$start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
/* 绘制居中缩放图像 */
$resize_img = imagecreatetruecolor($resize_w, $resize_h);
imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
$target_img = imagecreatetruecolor($target_w, $target_h);
imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
/* 将图片保存至文件 */
if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true);
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
imagejpeg($target_img, $target);
break;
case IMAGETYPE_PNG:
imagepng($target_img, $target);
break;
case IMAGETYPE_GIF:
imagegif($target_img, $target);
break;
}
return boolval(file_exists($target));
}

==================函数使用方式====================

// 原始图片的路径
$source = '../source/img/middle.jpg';
$width = 480; // 裁剪后的宽度
$height = 480;// 裁剪后的高度
// 裁剪后的图片存放目录
$target = '../source/temp/resize.jpg';
// 裁剪后保存到目标文件夹
if (image_center_crop($source, $width, $height, $target)) {
echo "<img src='$target'>";
}

==================图片裁剪效果====================

原图:1440*900

裁剪后:480*120

裁剪后:480*480

裁剪后:480*720

最新文章

  1. Linux下查看某进程相关进程
  2. NFS文件系统制作
  3. mysql常用函数参考
  4. Android使用SQLite数据库(3)
  5. 【练习】移动数据----infile *
  6. SQL Server 数据库操作类
  7. Dynamic Expression.Call Any
  8. Modular Inverse(模逆元,扩展欧几里德)
  9. Android安全–加强版Smali Log注入
  10. Python图像处理之验证码识别
  11. 福州大学软件工程1816 | W班 第7次作业成绩排名
  12. Git:git diff 命令详解
  13. android 2.3.4 编译中出错和解决办法
  14. CSS内容简单总结
  15. javascript计算字符串长度
  16. Jsonpath的写法
  17. c++ =&gt; new/delete
  18. jmeter随笔
  19. iOS读取info.plist中的值
  20. Oracle SQL语句优化34条

热门文章

  1. SQL语句(十三)多表查询
  2. 使用data:uri上传图片
  3. 小程序登录、微信网页授权(Java版)
  4. json 删除、添加对象
  5. F - Friends ZOJ - 3710(暴力)
  6. hibernate的一对多和多对一关联
  7. BAT脚本加防火墙455端口
  8. python psutil监控系统资源【转】
  9. 从TFS 删除工作项
  10. 002_tmux详解