php将png转为jpg,可设置压缩率

/**

 * 将PNG文件转换为JPG文件

 * @param $pngFilePath string PNG文件路径

 * @param $jpgFilePath string JPG文件路径

 * @param $quality int JPG质量,0-100,值越低,压缩率越高

 * @return void

 * @throws Exception

 */

function convertPngToJpg($pngFilePath, $jpgFilePath, $quality = 80)

{

    // 检查文件是否存在

    if (!file_exists($pngFilePath)) {

        throw new Exception("png文件不存在.");

    }

    // 创建一个新的 PNG 图像资源

    $pngImage = imagecreatefrompng($pngFilePath);

    if ($pngImage === false) {

        throw new Exception("无法创建png资源.");

    }

    // 创建一个新的真彩色图像(无透明度)

    $width = imagesx($pngImage);

    $height = imagesy($pngImage);

    $jpgImage = imagecreatetruecolor($width, $height);

    // 将 PNG 图像复制到真彩色图像上

    imagecopy($jpgImage, $pngImage, 0, 0, 0, 0, $width, $height);

    // 将图像保存为 JPG 文件

    if (!imagejpeg($jpgImage, $jpgFilePath, $quality)) {

        throw new Exception("保存jpg文件失败.");

    }

    // 销毁图像资源

    imagedestroy($pngImage);

    imagedestroy($jpgImage);

}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 22:06:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 22:06:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 22:06:02       58 阅读
  4. Python语言-面向对象

    2024-07-12 22:06:02       69 阅读

热门阅读

  1. XML标记语言简介

    2024-07-12 22:06:02       16 阅读
  2. C++学习

    C++学习

    2024-07-12 22:06:02      20 阅读
  3. makefile常用规则

    2024-07-12 22:06:02       18 阅读
  4. 固体物理学习笔记(持续更新

    2024-07-12 22:06:02       15 阅读
  5. 使用 docker-compose 部署和使用 Yapi

    2024-07-12 22:06:02       21 阅读
  6. 力扣 202快乐数

    2024-07-12 22:06:02       24 阅读
  7. 跨越数据边界:域适应在目标检测中的革新作用

    2024-07-12 22:06:02       25 阅读