php程序图片裁剪功能,已经集成函数(直接使用)

最近在开发小程序,在生成小程序朋友圈分享图的时候,需要裁剪原缩略图,所以就用到了下面的函数,可以直接使用,$catid,$id用来命名生成图片的名称,这样就不会重复生成。

/**
 * 裁剪图片
 * $src_img 图片源文件
 * $dst_w 目标图片宽
 * $dst_h 目标图片高
 * $catid ,$id 该文章id栏目id
 * @Linyufan.com
 * @2018.9.11
 */
function get_thumb_img($src_img,$dst_w,$dst_h,$catid,$id){
    //$src_img = ""; // 原图

    //$dst_w = 1240;
    //$dst_h = 700;

    list($src_w,$src_h)=getimagesize($src_img);  // 获取原图尺寸 
    $dst_scale = $dst_h/$dst_w; //目标图像长宽比
    $src_scale = $src_h/$src_w; // 原图长宽比 
    if ($src_scale>=$dst_scale){  // 过高
        $w = intval($src_w);
        $h = intval($dst_scale*$w);
     
        $x = 0;
        $y = ($src_h - $h)/3;
    } else { // 过宽
        $h = intval($src_h);
        $w = intval($h/$dst_scale);
     
        $x = ($src_w - $w)/2;
        $y = 0;
    }
     
    // 剪裁
    $source=imagecreatefromjpeg($src_img);
    $croped=imagecreatetruecolor($w, $h);
    imagecopy($croped, $source, 0, 0, $x, $y, $src_w, $src_h);
     
    // 缩放
    $scale = $dst_w / $w;
    $target = imagecreatetruecolor($dst_w, $dst_h);
    $final_w = intval($w * $scale);
    $final_h = intval($h * $scale);
    imagecopyresampled($target, $croped, 0, 0, 0, 0, $final_w,$final_h, $w, $h);
     
    // 保存
    imagejpeg($target, "/thumb/$catid-$id.jpg");
    imagedestroy($target);
}

 保存路径可以自己设定。

具体使用功能,参见小程序:林羽凡,

林羽凡小程序
林羽凡小程序

猜你喜欢

转载自blog.csdn.net/hamelong/article/details/82655687
今日推荐