【发布时间】:2020-04-25 14:01:05
【问题描述】:
我目前正在尝试使用 PHP-Imagick 将 ICO 文件转换为 16x16 像素的 PNG。到目前为止我尝试过的:
<?php
if (empty(\Imagick::queryFormats("ICO"))) {
throw new \Exception('Unsupported format');
}
$sourceFile = __DIR__ . '/favicon.ico';
$targetFile = __DIR__ . '/favicon.png';
$im = new \Imagick($sourceFile);
$im->writeImages($targetFile, true);
这部分有效。问题是,一个 ICO 文件可能包含多个图像,所以上面的代码创建了多个 PNG 文件
- favicon-0.png
- favicon-1.png
- ...
适用于各种尺寸。这没关系,但是,我需要找到接近 16x16 像素的那个,缩小它(如果需要)并删除所有其他的。为此,我已经尝试了一些事情,这就是我目前陷入困境的地方:
<?php
if (empty(\Imagick::queryFormats("ICO"))) {
throw new \Exception('Unsupported format');
}
$sourceFile = __DIR__ . '/favicon.ico';
$targetFile = __DIR__ . '/favicon.png';
$im = new \Imagick($sourceFile);
$count = $im->getNumberImages();
if ($count > 1) {
for ($x = 1; $x <= $count; $x++) {
$im->previousImage();
$tmpImageWidth = $im->getImageWidth();
$tmpImageHeight = $im->getImageHeight();
// ???
}
}
$im->writeImages($targetFile, true);
我想,我会通过反复试验找到一种可行的方法。但我想知道,是否有更简单的方法来实现这一点。
TL;DR:我需要一种简单的方法来将任意大小的 ICO 文件转换为 16x16 像素的 PNG,使用 PHP-Imagick(不能使用 GD)。
更新:
我的(目前有效,但可能不是最理想的)解决方案:
<?php
if (empty(\Imagick::queryFormats("ICO"))) {
throw new \Exception('Unsupported format');
}
$sourceFile = __DIR__ . '/favicon.ico';
$targetFile = __DIR__ . '/favicon.png';
$im = new \Imagick($sourceFile);
$count = $im->getNumberImages();
$targetWidth = $targetHeight = 16;
if ($count > 1) {
$images = [];
for ($x = 1; $x <= $count; $x++) {
$im->previousImage();
$images[] = [
'object' => $im,
'size' => $im->getImageWidth() + $im->getImageHeight()
];
}
$minSize = min(array_column($images, 'size'));
$image = array_values(array_filter($images, function($image) use ($minSize) {
return $minSize === $image['size'];
}))[0];
$im = $image['object'];
if ($image['size'] <> $targetWidth + $targetHeight) {
$im->cropThumbnailImage($targetWidth, $targetHeight);
}
}
else {
if ($im->getImageWidth() <> $targetWidth || $im->getImageHeight() <> $targetHeight) {
$im->cropThumbnailImage($targetWidth, $targetHeight);
}
}
$im->writeImage($targetFile);
【问题讨论】:
-
看起来你有一个可行的解决方案,干得好!将其作为答案并接受它为正确的并获得积分!
标签: php imagemagick imagick ico