引言

  1. 读取原始图片文件。
  2. 将图片加载到PHP资源中。
  3. 选择目标图片格式。
  4. 保存或输出转换后的图片。

准备工作

在开始之前,请确保您的PHP环境已经安装了GD库。大多数PHP安装默认已经包含了GD库,但您可以通过以下命令检查:

<?php
if (function_exists('gd_info')) {
    $gd_version = gd_info();
    echo "GD库版本: " . $gd_version['GD Version'] . "\n";
} else {
    echo "GD库未安装或不可用。\n";
}
?>

图片读取与加载

<?php
$imagePath = 'path/to/your/image.jpg'; // 替换为您的图片路径
$imageResource = imagecreatefromjpeg($imagePath); // 根据图片格式选择相应的函数,如imagecreatefrompng()

if ($imageResource === false) {
    die('无法读取图片文件:' . $imagePath);
}
?>

图片格式转换

<?php
$targetPath = 'path/to/your/converted_image.png';
imagepng($imageResource, $targetPath); // 保存为PNG格式
imagedestroy($imageResource); // 释放图片资源
?>
<?php
imagejpeg($imageResource, $targetPath); // 保存为JPEG格式
imagedestroy($imageResource); // 释放图片资源
?>

高级功能

<?php
$width = 100; // 目标宽度
$height = 100; // 目标高度

// 计算宽高比以保持图片比例
$oldWidth = imagesx($imageResource);
$oldHeight = imagesy($imageResource);
$ratio = $width / $oldWidth;
$newHeight = $oldHeight * $ratio;

// 创建新图片资源
$newImageResource = imagecreatetruecolor($width, $newHeight);

// 裁剪和调整大小
imagecopyresampled($newImageResource, $imageResource, 0, 0, 0, 0, $width, $newHeight, $oldWidth, $oldHeight);

// 保存新图片
imagepng($newImageResource, $targetPath);
imagedestroy($newImageResource);
imagedestroy($imageResource);
?>

总结