PHP

PHP如何实现图像的无损压缩

小樊
106
2024-07-22 13:08:04
栏目: 编程语言

PHP可以使用GD库来实现图像的无损压缩。下面是一个简单的示例代码:

<?php
// 原始图像文件
$source_file = 'input.jpg';

// 目标图像文件
$target_file = 'output.jpg';

// 打开原始图像文件
$source = imagecreatefromjpeg($source_file);

// 创建一个空白的目标图像
$target = imagecreatetruecolor(imagesx($source), imagesy($source));

// 无损压缩
imagecopy($target, $source, 0, 0, 0, 0, imagesx($source), imagesy($source));

// 保存目标图像到文件
imagejpeg($target, $target_file);

// 释放资源
imagedestroy($source);
imagedestroy($target);

echo '图像无损压缩完成';
?>

以上代码会将原始图像文件input.jpg进行无损压缩,并保存为output.jpg文件。您可以根据实际需求调整压缩比例和输出文件格式。

0
看了该问题的人还看了