前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >php图片裁剪函数

php图片裁剪函数

作者头像
砸漏
发布2020-10-20 15:01:23
2.2K0
发布2020-10-20 15:01:23
举报
文章被收录于专栏:恩蓝脚本

本文实例为大家分享了php图片裁剪函数的具体代码,供大家参考,具体内容如下

代码语言:javascript
复制
/*
 * 图片裁剪工具
 * 将指定文件裁剪成正方形
 * 以中心为起始向四周裁剪
 * @param $src_path string 源文件地址
 * @param $des_path string 保存文件地址
 * @param $des_w double 目标图片宽度
 * */
function img_cut_square($src_path,$des_path,$des_w=100){
  $img_info = getimagesize($src_path);//获取原图像尺寸信息
  $img_width = $img_info[0];//原图宽度
  $img_height = $img_info[1];//原图高度
  $img_type = $img_info[2];//图片类型 1 为 GIF 格式、 2 为 JPEG/JPG 格式、3 为 PNG 格式
  if($img_type != 2 && $img_type != 3) return ;

  /*计算缩放尺寸*/
  if($img_height   $img_width){
    $scale_width = $des_w;//缩放宽度
    $scale_height = round($des_w / $img_width * $img_height);//缩放高度

    $src_y = round(($scale_height - $des_w)/2);
    $src_x = 0;
  }else{
    $scale_height = $des_w;
    $scale_width = round($des_w / $img_height * $img_width);

    $src_y = 0;
    $src_x = round(($scale_width - $des_w)/2);
  }

  $dst_ims = imagecreatetruecolor($scale_width, $scale_height);//创建真彩画布
  $white = imagecolorallocate($dst_ims, 255, 255, 255);
  imagefill($dst_ims, 0, 0, $white);
  if($img_type == 2){
    $src_im = @imagecreatefromjpeg($src_path);//读取原图像
  }else if($img_type == 3){
    $src_im = @imagecreatefrompng($src_path);//读取原图像
  }

  imagecopyresized($dst_ims, $src_im, 0, 0 ,0, 0 , $scale_width , $scale_height , $img_width,$img_height);//缩放图片到指定尺寸


  $dst_im = imagecreatetruecolor($des_w, $des_w);
//  $white = imagecolorallocate($dst_im, 255, 255, 255);
//  imagefill($dst_im, 0, 0, $white);
  imagecopy($dst_im, $dst_ims, 0, 0, $src_x, $src_y, $des_w, $des_w);//开始裁剪图片为正方形
// imagecopyresampled($dst_im, $src_im, $src_x, $src_y, 0, 0, $real_width, $real_width,$img_width,$img_height);
  if($img_type == 2) {
    imagejpeg($dst_im, $des_path);//保存到文件
  }else if($img_type == 3){
    imagepng($dst_im,$des_path);
  }
//  imagejpeg($dst_im);//输出到浏览器
  imagedestroy($dst_im);
  imagedestroy($dst_ims);
  imagedestroy($src_im);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持网站事(zalou.cn)。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-12-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档