栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用PHP缩放图像并保持宽高比

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用PHP缩放图像并保持宽高比

我为完成的另一个项目编写了这样的代码。我已在下面复制了它,可能需要修补一下!(它确实需要GD库)

这些是它需要的参数:

$image_name - Name of the image which is uploaded$new_width - Width of the resized photo (maximum)$new_height - Height of the resized photo (maximum)$uploadDir - Directory of the original image$moveToDir - Directory to save the resized image

它将按比例缩小或放大图像到最大宽度或高度

function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir){    $path = $uploadDir . '/' . $image_name;    $mime = getimagesize($path);    if($mime['mime']=='image/png') {         $src_img = imagecreatefrompng($path);    }    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {        $src_img = imagecreatefromjpeg($path);    }    $old_x          =   imageSX($src_img);    $old_y          =   imageSY($src_img);    if($old_x > $old_y)     {        $thumb_w    =   $new_width;        $thumb_h    =   $old_y*($new_height/$old_x);    }    if($old_x < $old_y)     {        $thumb_w    =   $old_x*($new_width/$old_y);        $thumb_h    =   $new_height;    }    if($old_x == $old_y)     {        $thumb_w    =   $new_width;        $thumb_h    =   $new_height;    }    $dst_img        =   ImageCreateTrueColor($thumb_w,$thumb_h);    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);    // New save location    $new_thumb_loc = $moveToDir . $image_name;    if($mime['mime']=='image/png') {        $result = imagepng($dst_img,$new_thumb_loc,8);    }    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {        $result = imagejpeg($dst_img,$new_thumb_loc,80);    }    imagedestroy($dst_img);     imagedestroy($src_img);    return $result;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421716.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号