php 生成等比例缩略图,php等比例生成缩略图的完美方法

宝哥软件园需要php等比生成图片缩略图,在网上找了一下,发现大部分代码都不能正常使用,有些只是jpg图片生成缩略图的函数,对于gif和png并不能完美实现,生成png以后会出现打不开的情况,所以做了一下小小的修改,可以完美的实现gif ,jpg,png三种图片的生成缩略图。记录一下函数。function reSizeImg($imgSrc, $dstimg, $resize_width, $resize_height, $isCut = false) {

//图片的类型

$type = substr(strrchr($imgSrc, "."), 1);

//初始化图象

if ($type == "jpg" || $type == "jpeg") {

$im = imagecreatefromjpeg($imgSrc);

}

if ($type == "gif") {

$im = imagecreatefromgif($imgSrc);

}

if ($type == "png") {

$im = imagecreatefrompng($imgSrc);

}

$width = imagesx($im);

$height = imagesy($im);

//生成图象

//改变后的图象的比例

$resize_ratio = ($resize_width) / ($resize_height);

//实际图象的比例

$ratio = ($width) / ($height);

if (($isCut) == 1) {

if ($ratio >= $resize_ratio) {

//高度优先

$newimg = imagecreatetruecolor($resize_width, $resize_height);

imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, (($height) * $resize_ratio), $height);

createImg($type, $newimg, $dstimg);

}

if ($ratio 

//宽度优先

$newimg = imagecreatetruecolor($resize_width, $resize_height);

imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, $width, (($width) / $resize_ratio));

createImg($type, $newimg, $dstimg);

}

} else {

if ($ratio >= $resize_ratio) {

$newimg = imagecreatetruecolor($resize_width, ($resize_width) / $ratio);

imagecopyresampled($newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height);

createImg($type, $newimg, $dstimg);

}

if ($ratio 

$newimg = imagecreatetruecolor(($resize_height) * $ratio, $resize_height);

imagecopyresampled($newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height);

createImg($type, $newimg, $dstimg);

}

}

ImageDestroy($im);

}

function createImg($type, $newimg, $dstimg)

{

//初始化图象

if ($type == "jpg" || $type == "jpeg") {

imagejpeg($newimg, $dstimg);

}

if ($type == "gif") {

imagegif($newimg, $dstimg);

}

if ($type == "png") {

imagepng($newimg, $dstimg);

}

}

调用方法:reSizeImg($原图地址,$新图地址,300,200);

这样就可以实现等比例成生成缩略图了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值