php 处理图片比例,php – 计算图像大小比例以调整大小

这里的代码从我的个人抓包图像调整大小的代码。首先,您需要的数据:

list($originalWidth, $originalHeight) = getimagesize($imageFile);

$ratio = $originalWidth / $originalHeight;

然后,该算法将图像尽可能适合目标尺寸,保持原始的宽高比,不将图像拉伸大于原始尺寸:

$targetWidth = $targetHeight = min($size, max($originalWidth, $originalHeight));

if ($ratio < 1) {

$targetWidth = $targetHeight * $ratio;

} else {

$targetHeight = $targetWidth / $ratio;

}

$srcWidth = $originalWidth;

$srcHeight = $originalHeight;

$srcX = $srcY = 0;

这将裁剪图像以完全填充目标大小,而不是拉伸它:

$targetWidth = $targetHeight = min($originalWidth, $originalHeight, $size);

if ($ratio < 1) {

$srcX = 0;

$srcY = ($originalHeight / 2) - ($originalWidth / 2);

$srcWidth = $srcHeight = $originalWidth;

} else {

$srcY = 0;

$srcX = ($originalWidth / 2) - ($originalHeight / 2);

$srcWidth = $srcHeight = $originalHeight;

}

这实际上调整大小:

$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);

imagecopyresampled($targetImage, $originalImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

在这种情况下,$ size只是宽度和高度(平方目标大小)的一个数字。我相信你可以修改它使用非正方形的目标。它还应该给你一个灵感,你可以使用什么其他调整大小的算法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值