#php #imagemagick #imagick #concrete5
#php #imagemagick #imagick #concrete5
Вопрос:
Я новый разработчик на готовом сайте, пытающийся выяснить, как использовать настроенный инструмент ImageMagick. Способ, которым мы это используем, заключается в автоматическом изменении цвета продуктов с помощью фильтра HALD CLUT.
Я запустил его вчера, но на выходных изображениях повсюду черные линии. Я тестировал изменение типа / формата файла на изображении продукта и фильтра HALD CLUT, но безуспешно, поэтому я предполагаю, что это как-то связано с ImageMagick.
Снимок экрана выводимого изображения
У кого-нибудь есть идеи, что могло бы вызвать это?
Вот код для генератора цвета ImageMagick:
class SwatchGenerator {
public $mask;
public $swatches;
public $types;
public $th;
public $base_url;
public $results;
public $type;
public $color;
public $output;
function __construct ($overwrite = false) {
$this->th = Loader::helper('text');
$this->base_url = View::url('/');
$this->overwrite = $overwrite;
$this->delimiter = '~';
$this->results = [];
$this->loadSwatches();
$this->loadTypes();
}
function loadSwatches () {
$swatches = Express::getObjectByHandle('swatch')->getEntries();
foreach ($swatches as $swatch) {
$handle = $this->th->urlify($swatch->getSwatchName());
$filter = $swatch->getSwatchFilter();
$this->swatches[$handle] = (is_object($filter)) ? $this->getImagickInstance($filter) : false;
}
}
function loadTypes () {
$types = ConcreteCoreFileImageThumbnailTypeType::getVersionList();
foreach ($types as $type) {
$type_handle = $type->getHandle();
if (strpos($type_handle, '_2x') === false amp;amp; strpos($type_handle, 'product_') !== false) {
$this->types[$type_handle] = $type;
}
}
}
function setType ($type) {
$this->type = $type;
}
function setColor ($color) {
$this->color = $color;
}
function setOutput ($output) {
$this->output = $output;
}
function log ($message) {
$this->addResult($message);
// Log::addEntry($message);
}
function addResult ($message) {
$this->results[] = $message;
}
function getResults () {
return $this->results;
}
function getResultLog ($delimiter = "nr") {
return implode("nr", $this->getResults());
}
function generate ($base_file, $allowed_type = false) {
$mask_file = $base_file->getAttribute('color_mask');
if (!is_object($mask_file)) {
$this->log('Mask not found.');
return;
}
if ($base_file->getAttribute('width') != 2560) {
$this->log('Invalid image size found. Must be 2560px wide.');
return;
}
// these are our core images that should not change for any swatch
$base = $this->getImagickInstance($base_file);
// we do this to remove any trace of transparency and flatten the file
// resolves issues with odd masking we were seeing
$base->setImageBackgroundColor('white');
// $base->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$base->setImageAlphaChannel(11);
$base->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
// jpg output
$base->setImageFormat('jpg');
$base->setImageCompressionQuality(85);
$mask = $this->getImagickInstance($mask_file);
$overlay = clone ($base);
$overlay->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
// base path to write the swatches to
$base_file = $this->parsePath($base_file->getRelativePath());
$pathinfo = pathinfo($base_file);
// stores our composited swatch images
$swatches = [];
// now create an image for each swatch we have
foreach ($this->swatches as $swatch_handle => $filter) {
// if we are limited to a color, then abort if we are not on it
if ($this->color amp;amp; $this->color != $swatch_handle) {
continue;
}
$swatch = clone ($base);
if ($filter) {
$swatch->haldClutImage($filter);
}
$swatch->compositeImage($overlay, imagick::COMPOSITE_DEFAULT, 0, 0);
$swatches[$swatch_handle] = $swatch;
foreach ($this->types as $type_handle => $type) {
// filter non-product types
if ($allowed_type amp;amp; $allowed_type !== $type_handle) {
continue;
}
// if we are limited to a type, then abort if we are not on it
if ($this->type amp;amp; $this->type != $type_handle) {
continue;
}
$output_path = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . $this->delimiter . $type_handle . $this->delimiter . $swatch_handle . '.jpg';
if (file_exists($output_path) amp;amp; !$this->overwrite) {
$this->log('Skipping existing file at ' . $output_path);
} else {
$this->log('Rendering ' . $this->th->unhandle($swatch_handle) . ' at ' . $type->getWidth() . 'px (' . $type_handle . ')');
$output = clone ($swatch);
$output->resizeImage($type->getWidth(), 0, Imagick::FILTER_LANCZOS, 0);
$output->writeImage('../' . $output_path);
if ($this->output) {
$this->addResult("<img src='/{$output_path}' />");
}
}
}
}
}
function getImagickInstance ($file, $type = false) {
if (is_object($file)) {
$path = ($type) ? $file->getThumbnailURL($type) : $file->getRelativePath();
$image = new Imagick($this->parsePath('../' . $path));
$image->setImageFormat('png');
$image->setFormat('png');
return $image;
}
}
function parsePath ($path) {
// strip leading slash
$path = preg_replace('/^//', '', $path);
return str_replace($base_url, '', $path);
}
}
Я использую PHP версии 7.0.3.3, Imagick версии 3.4.3 и ImageMagick 6.9.6-2.
Комментарии:
1. Можете ли вы опубликовать свое входное изображение и изображение HALD, чтобы мы могли протестировать в командной строке? Ваша версия ImageMagick очень старая. Я предлагаю вам попробовать обновить.
2.Вот изображения:imgur.com/udcGu9F imgur.com/QdZMMc7 Я рассмотрю возможность обновления. Мы также используем более старую версию PHP, поэтому я не уверен, какая версия поддерживается выше. Спасибо за ответ!
3. Кажется, я не могу загрузить ваше первое связанное изображение
Ответ №1:
Я не могу получить доступ к вашему исходному изображению. Но я загрузил ваше изображение Hald. Итак, я применил это к следующему изображению в ImageMagick 6.9.11.28 Q16 Mac OSX в командной строке, и оно работает нормально — по крайней мере, без строк. Итак, я подозреваю, что проблема в вашей версии ImageMagick или версии Imagick или в вашем коде. Вы могли бы попробовать запустить мою команду в PHP exec () и посмотреть, работает ли это. Он сообщит вам, работает ли ImageMagick должным образом или нет. Это также может быть проблема с вашим входным изображением или версией делегата libpng.
Ввод:
Изображение Hald:
convert lena.jpg hald.png -hald-clut result.png