1

:) 我在另一篇文章中发现了这一行代码,它使用 pngquant 成功压缩了图像。问题是,它输出具有不同名称的优化图像(显然是为了保留原始图像)。

我试图找到一种方法:

a) 添加最低质量参数 60 b) 使用 if/else 语句允许用户选择覆盖现有文件或输出新的优化图像(用户指定的名称)

谢谢你!ntlri - 不要长时间阅读它

<?php system('pngquant --quality=85 image.png'); ?>

所以我尝试过的是以下..由于某种原因,单引号需要是双引号才能正确解析变量..

<?php

$min_quality = 60; $max_quality = 85;

$keep_original = 'dont_keep';

if ($keep_original == 'keep') {

    $image_name = 'image.png';

    $path_to_image = 'images/' . $image_name;

    $new_file = 'image2.png';

    $path_to_new_image = 'images/' . $new_file;

    // don't know how to output to specified $new_file name
    system("pngquant --quality=$min_quality-$max_quality $path_to_image");

} else {

    $image_name = 'image.png';

    $path_to_image = 'images/' . $image_name;

    // don't know if you can overwrite file by same name as additional parameter
    system("pngquant --quality=$min_quality-$max_quality $path_to_image");

    // dont't know how you get the name of the new optimised image
    $optimised_image = 'images/' . $whatever_the_optimised_image_is_called;

    rename($optimised_image, $image_name);

    unlink($optimised_image);
}

?>
4

2 回答 2

1

我与开发 pngquant 的小伙子pornel 进行了交谈。它实际上比我之前写的要简单得多......

!重要 - 使用 escapeshellarg() 非常重要,否则人们可以通过上传具有特殊文件名的文件来接管您的服务器。

$image_name = 'image.png';

$target_file = 'images/' . $image_name;

$existing_image = 'image.png'; // image already on server if applicable

$keep = 'keep';

$target_escaped = escapeshellarg($target_file);

if ($keep == 'keep') {

    // process/change output file to image_compressed.png keeping both images
    system("pngquant --force --quality=70 $target_escaped --ext=_compressed.png");

    $remove_ext = substr($newFileName, 0 , (strrpos($newFileName, ".")));

// $new_image is just the name (image_compressed.png) if you need it    
$new_image = $remove_ext . '_compressed.png';

    // remove old file if different name
    if ($existing_image != $newFileName) {

    $removeOld = '../images/' . $existing_image; 

    unlink($removeOld);

    } // comment out if you want to keep existing file

} else {

    // overwrite if file has the same name
    system("pngquant --force --quality=70 $target_escaped --ext=.png");

    // remove old file if different name
    if ($existing_image != $newFileName) {

    $removeOld = '../images/' . $existing_image; 

    unlink($removeOld);

    }

    $new_image = $newFileName;
}
于 2017-03-26T13:54:59.647 回答
1

来自该程序的文档:

输出文件名与输入名称相同,只是\n\ 以 \"-fs8.png\"、\"-or8.png\" 或您的自定义扩展名结尾

所以,对于这个问题:

// don't know how to output to specified $new_file name
system("pngquant --quality=$min_quality-$max_quality $path_to_image");

要选择一个新名称,假设您正在压缩图像name.png

--ext=_x.png

这将创建一个名为的新图像name_x.png

所以,你$new_file只是一个后缀,

$new_file = '_x.png'; // to choose new file name name_x.png

// 不知道是否可以覆盖与附加参数同名的文件

如程序文档中所述,新文件名将以-fs8.pngor为后缀-or8.png,因此您可以重命名将使用此后缀生成的文件,或者只需将--ext选项设置为 :.png这将附加到原始文件中

--ext=.png

有关更多详细信息,请查看存储库

于 2017-03-26T10:36:56.890 回答