温馨提示×

php imagecopyresized 在 jpg 上效果

PHP
小樊
102
2024-12-06 02:07:53
栏目: 编程语言

imagecopyresized 是 PHP 中一个用于调整图像大小的函数,它可以将一张图片按比例或指定大小复制到另一张图片上

以下是一个使用 imagecopyresized 调整 JPEG 图像大小的示例:

<?php // 加载原始图像和目标图像 $sourceImage = imagecreatefromjpeg('source.jpg'); $destinationImage = imagecreatetruecolor(300, 200); // 保持 PNG 和 GIF 图像的透明度 imagealphablending($destinationImage, false); imagesavealpha($destinationImage, true); // 获取原始图像和目标图像的尺寸 $sourceWidth = imagesx($sourceImage); $sourceHeight = imagesy($sourceImage); $destinationWidth = 300; $destinationHeight = 200; // 计算缩放比例 $scaleX = $destinationWidth / $sourceWidth; $scaleY = $destinationHeight / $sourceHeight; $scale = min($scaleX, $scaleY); // 计算新的尺寸 $newWidth = intval($sourceWidth * $scale); $newHeight = intval($sourceHeight * $scale); // 将原始图像按比例缩放到目标图像上 imagecopyresized($destinationImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight); // 保存调整大小后的图像 imagejpeg($destinationImage, 'resized_image.jpg', 80); // 销毁图像资源 imagedestroy($sourceImage); imagedestroy($destinationImage); ?> 

在这个示例中,我们首先加载了名为 source.jpg 的原始 JPEG 图像,然后创建了一个名为 destinationImage 的新图像,其尺寸为 300x200 像素。接下来,我们使用 imagecopyresized 函数将原始图像按比例缩放到目标图像上,并将结果保存为名为 resized_image.jpg 的新 JPEG 图像。最后,我们销毁了所有图像资源。

0