php将图片等比例缩放,php 实现图片的等比例缩放

新建index.php,然后指定文件图片名称

/**

* 图片等比缩放

*

* @param $src_file

* @param $des_w

* @param $des_h

*/

function thrumb($src_file, $des_w, $des_h) {

list($width, $height, $imgTypeNumber) = getimagesize($src_file);

//处理图片创建函数和图片输出函数

switch ($imgTypeNumber) {

case 1://gif

$imageCreateFrom = 'imagecreatefromgif';

$imageOut        = 'imagegif';

$type            = 'gif';

break;

case 2://jpg

$imageCreateFrom = 'imagecreatefromjpeg';

$imageOut = 'imagejpeg';

$type = 'jpg';

break;

case 3://png

$imageCreateFrom = 'imagecreatefrompng';

$imageOut        = 'imagepng';

$type            = 'png';

break;

case 4:  //bmp

$imageCreateFrom = 'imagecreatefrombmp';

$imageOut        = 'imagewbmp';

$type            = 'bmp';

break;

}

//计算缩放宽高

if (($width/$height) >= ($des_w / $des_h)){

$des_wid = $des_w;

$des_hei = intval($des_w * $height / $width);

$mid_x   = 0;

$mid_y   = intval(($des_h - $des_hei) / 2);

} else {

$des_wid = intval($des_h * $width / $height);

$des_hei = $des_h;

$mid_x   = intval(($des_w - $des_wid) / 2);

$mid_y   = 0;

}

$newImg  = imagecreatetruecolor($des_w, $des_h);

$white   = imagecolorallocate($newImg, 255,255, 255);

imagefill($newImg, 0, 0, $white);

$img     = $imageCreateFrom($src_file);

$imgName = strtotime(date('YmdHis'));

//缩放

imagecopyresampled($newImg, $img, $mid_x, $mid_y, 0, 0, $des_wid, $des_hei, $width, $height);

$imgSrc  = $imgName . '.' . $type;

$imageOut($newImg, $imgSrc);

imagedestroy($img);

imagedestroy($newImg);

}

thrumb("images/A1L2GBULgcL._AC_UL1500_-787x1024.jpg", 500, 500);

缩放前的图片:

7a6206fb823b06b519b6c64cdc3ef6c2.png

代码运行后缩放的图片:

5c25c4cc638e474079be524231180ed5.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值