PHP: полный мануал с примерами, функциями и ООП
Практический мануал PHP: от переменных и читаемого кода до безопасных форм, интеграций, базы данных и ООП на примере магазина. Учебный маршрут, поиск функций, подробные примеры, разбор ошибок и исходники для скачивания.

Дерево руководства
Глава 319 · От первого файла до production-границ
Imagick: файлы, blob, stream, format, metadata и запись
Полный договор 40 методов ввода/вывода: ping/read, file handle, blob, filename/format, properties/profiles, strip и одно- либо многокадровая запись.
Сначала задача и первый управляемый результат
Нужно безопасно провести изображение от локального файла или ограниченного upload payload до проверенного результата, не перепутав путь, binary bytes, stream, object state и encoder format.
Перед примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Осознанный выбор path, blob или stream
- Лёгкую предварительную проверку через ping без ложного обещания безопасности
- Явное управление format, filename, profiles и properties
- Запись одного кадра или всей sequence с проверкой ошибки
Пять разных вещей: файл, bytes, stream, объект и format
| Сущность | Что это в примерах | Главная ошибка |
|---|---|---|
| Файл | Путь к JPEG/PNG/TIFF на диске | Принять пользовательский путь без canonical allowlist |
| Blob/bytes | Бинарная PHP-строка | Печатать как текст или держать огромный payload в памяти |
| Stream | Открытый binary handle с позицией | Забыть проверить mode, rewind и seekability |
| Imagick object | Декодированные кадры и настройки wand | Считать его просто именем файла |
| Format | Coder, который читает/пишет bytes | Определять его только по расширению пути |
Аналогия с контейнером помогает различить уровни, но не описывает внутреннюю память: ImageMagick может держать pixel cache в heap, map или на диске по policy.
Практический маршрут: upload → worker → публичный файл
Один и тот же PNG можно передать как путь, binary string или открытый stream. После чтения Imagick хранит декодированный object; перед выдачей его снова кодируют в выбранный format. Эти переходы нельзя смешивать: расширение пути, MIME, image format и object filename отвечают на разные вопросы.
- PHP принимает upload и проверяет upload error, размер и временный локальный путь
- finfo/allowlist отсеивают неподходящий тип; Imagick policy остаётся второй границей
- ping читает базовые свойства, приложение ограничивает пиксели и кадры
- read декодирует input в ограниченном worker; ImagickException завершает задание
- формат и нужные профили выбираются явно; output пишется во временный файл
- сервер проверяет итог и делает atomic rename в публичный каталог
| API входа/выхода | Плюс | Цена/риск |
|---|---|---|
| readImage(path) | простой локальный путь и decoder context | путь требует canonical allowlist |
| readImageBlob(bytes) | не нужен постоянный input file | payload целиком находится в PHP memory |
| readImageFile(handle) | удобен controlled tmp stream | mode, position, seekability и temp permissions |
| getImageBlob() | байты одного кадра сразу | ещё одна полная binary string в памяти |
| writeImageFile(handle) | потоковый output без скрытого пути | нужен writable handle и явный format |
Где должен остановиться pipeline
| Граница | Проверка | Решение |
|---|---|---|
| До Imagick | размер upload, canonical path, allowlist MIME/extension | отклонить запрос без decoder |
| До полного read | queryFormats, ping, число пикселей/кадров | отправить в ограниченный worker или отказать |
| Во время обработки | resource policy, progress/timeout, ImagickException | прервать задание и сохранить диагностический код |
| Перед публикацией | format, MIME, профили, путь temp/output | atomic rename только проверенного результата |
Полный указатель методов этого модуля
artifact
deleteImageArtifact · getImageArtifact · setImageArtifact
blob
blob-sequence
filename
getFilename · getImageFilename · setFilename · setImageFilename
format
getFormat · getImageFormat · getImageMimeType · setFormat · setImageFormat
identify
identifyFormat · identifyImage
metadata
ping
ping-handle
profile
getImageProfile · getImageProfiles · profileImage · removeImageProfile · setImageProfile
property
deleteImageProperty · getImageProperties · getImageProperty · setImageProperty
read
read-blob
read-handle
read-many
strip
write
write-handle
write-handle-many
write-many
Функции и методы этой темы
Откройте карточку, чтобы увидеть договор функции, примеры, ограничения и связанные инструменты.
Imagick::commentImageКомментарий становится метаданными поддерживающего формата.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::commentImage(string $comment): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно добавить короткий комментарий к текущему кадру перед экспортом
- Метод получает явно подготовленное состояние и параметры
- После вызова комментарий становится метаданными поддерживающего формата
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Добавить короткий комментарий к текущему кадру перед экспортом.
Сигнатура. Imagick::commentImage(string $comment): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $comment | Короткий несекретный комментарий для metadata.Точная формулировка PHP ManualThe comment to add |
Возврат и видимый итог. Комментарий становится метаданными поддерживающего формата.
Соседний выбор. setImageProperty() для именованного свойства.
Точные соседние карточки. Imagick::labelImage.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->commentImage('Preview generated by image worker');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::commentImage',
'returned' => aenObserve('Imagick::commentImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: комментарий становится метаданными поддерживающего формата. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->commentImage('Order 42 public preview');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$storedComment = $image->getImageProperty('comment');
$observation = [
'method' => 'Imagick::commentImage',
'returned' => aenObserve('Imagick::commentImage', $result),
'effect' => aenObserve('Imagick::commentImage:effect', $storedComment),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: комментарий становится метаданными поддерживающего формата. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Adds a comment to your image
Description: Adds a comment to your image.
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page affb2412a2de4584ccd53025690879d61c096af6ae20067dbd9de12951e9d938; XML 3c1ae6a4a8af3a8002042461f83ca1e26c82037f02b68d32800c254d1fb8980f.
Imagick::deleteImageArtifactУказанный key перестаёт влиять на дальнейшую операцию.
PECL imagick 3 · imagick
Imagick::deleteImageArtifact(string $artifact): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно убрать временный artifact конкретного кадра перед следующим этапом
- Метод получает явно подготовленное состояние и параметры
- После вызова указанный key перестаёт влиять на дальнейшую операцию
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Убрать временный artifact конкретного кадра перед следующим этапом.
Сигнатура. Imagick::deleteImageArtifact(string $artifact): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $artifact | Точное имя внутреннего artifact ImageMagick.Точная формулировка PHP ManualThe name of the artifact to delete |
Возврат и видимый итог. Указанный key перестаёт влиять на дальнейшую операцию.
Соседний выбор. setImageArtifact() с новым значением либо новый чистый объект.
Точные соседние карточки. Imagick::setImageArtifact · Imagick::getImageArtifact.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageArtifact('compose:args', '640x480+0+0');
$result = $image->deleteImageArtifact('compose:args');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::deleteImageArtifact',
'returned' => aenObserve('Imagick::deleteImageArtifact', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: указанный key перестаёт влиять на дальнейшую операцию. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageArtifact('distort:viewport', '640x480+0+0');
$result = $image->deleteImageArtifact('distort:viewport');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$artifactRemoved = $image->getImageArtifact('distort:viewport') === '';
$observation = [
'method' => 'Imagick::deleteImageArtifact',
'returned' => aenObserve('Imagick::deleteImageArtifact', $result),
'effect' => aenObserve('Imagick::deleteImageArtifact:effect', $artifactRemoved),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: указанный key перестаёт влиять на дальнейшую операцию. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Delete image artifact
Description: Deletes an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. Available since Imagick 6.5.7.
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: Imagick::setImageArtifact, Imagick::getImageArtifact
Source hashes: page ba7abde110b0f42be0a5d22349a998f5f7138da307536b113df35f9bbe252063; XML 4fdfda06d4bd4228b8c661a8d38c345e3d10a563503d696ab734ea405ec7590e.
Imagick::deleteImagePropertyВыбранное property исчезает из текущего кадра.
PECL imagick 3 >= 3.3.0 · imagick
Imagick::deleteImageProperty(string $name): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно удалить одно именованное свойство, не стирая все профили
- Метод получает явно подготовленное состояние и параметры
- После вызова выбранное property исчезает из текущего кадра
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Удалить одно именованное свойство, не стирая все профили.
Сигнатура. Imagick::deleteImageProperty(string $name): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка.Точная формулировка PHP ManualThe name of the property to delete. |
Возврат и видимый итог. Выбранное property исчезает из текущего кадра.
Соседний выбор. stripImage() только когда допустимо удалить всё.
Точные соседние карточки. Imagick::getImageProperties · Imagick::getImageProperty.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageProperty('exif:GPSLatitude', '37/1,37/1,0/1');
$result = $image->deleteImageProperty('exif:GPSLatitude');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::deleteImageProperty',
'returned' => aenObserve('Imagick::deleteImageProperty', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: выбранное property исчезает из текущего кадра. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageProperty('exif:GPSLongitude', '37/1,37/1,0/1');
$result = $image->deleteImageProperty('exif:GPSLongitude');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$gpsRemoved = $image->getImageProperty('exif:GPSLongitude') === '';
$observation = [
'method' => 'Imagick::deleteImageProperty',
'returned' => aenObserve('Imagick::deleteImageProperty', $result),
'effect' => aenObserve('Imagick::deleteImageProperty:effect', $gpsRemoved),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: выбранное property исчезает из текущего кадра. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 3 >= 3.3.0 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Deletes an image property
Description: Deletes an image property.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 5626fff7cc91d25d19fd9c6b24127fdf856b0b1adb8c4ca148b4852ed7c33f4c; XML f409bf6ec7d06cabfc820003c32dc4c21dc8c5b0885a07d4a37a9ecd280e5d82.
Imagick::getFilenameВозвращается объектное имя файла.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getFilename(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно узнать filename, связанный со всей последовательностью/wand
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается объектное имя файла
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Узнать filename, связанный со всей последовательностью/wand.
Сигнатура. Imagick::getFilename(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Возвращается объектное имя файла.
Соседний выбор. getImageFilename() для текущего кадра.
Точные соседние карточки. Imagick::getImageFilename · Imagick::setFilename.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getFilename();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getFilename',
'returned' => aenObserve('Imagick::getFilename', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается объектное имя файла. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getFilename();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$objectFilename = $result;
$currentFrameFilename = $image->getImageFilename();
$observation = [
'method' => 'Imagick::getFilename',
'returned' => aenObserve('Imagick::getFilename', $result),
'effect' => aenObserve('Imagick::getFilename:effect', $currentFrameFilename),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается объектное имя файла. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: The filename associated with an image sequence
Description: Returns the filename associated with an image sequence.
Return: Returns a string on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 4030a5c107c3df1206193a91b65359840ec0ab4fa65b2de606d38a1cbde14fa7; XML 5af0bacc8d969890d1c85d09fa84a1f2f14b1a6515bca243c34d63defa08bec3.
Imagick::getFormatВозвращается короткое имя container format.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getFormat(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно узнать объектный формат последовательности
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается короткое имя container format
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Узнать объектный формат последовательности.
Сигнатура. Imagick::getFormat(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Возвращается короткое имя container format.
Соседний выбор. getImageFormat() для конкретного изображения.
Точные соседние карточки. Imagick::getImageFormat · Imagick::getImageMimeType.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setFormat('ppm');
$result = $image->getFormat();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getFormat',
'returned' => aenObserve('Imagick::getFormat', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается короткое имя container format. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setFormat('ppm');
$result = $image->getFormat();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$objectFormat = strtoupper($result);
$frameFormat = $image->getImageFormat();
$observation = [
'method' => 'Imagick::getFormat',
'returned' => aenObserve('Imagick::getFormat', $result),
'effect' => aenObserve('Imagick::getFormat:effect', $frameFormat),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается короткое имя container format. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the format of the Imagick object
Description: Returns the format of the Imagick object.
Return: Returns the format of the image.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 2dd25443865df753d44b3eea3fe817e3b9c36557fefecfd12cb68b28b53d9db2; XML 2c046372ffc77c678dbfb4138d274b8933d6abd935e8a89ef43bbcb9d32419c3.
Imagick::getImageArtifactВозвращается строковое значение управляющего параметра.
PECL imagick 3 · imagick
Imagick::getImageArtifact(string $artifact): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно прочитать внутренний artifact текущего кадра по точному ключу
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается строковое значение управляющего параметра
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Прочитать внутренний artifact текущего кадра по точному ключу.
Сигнатура. Imagick::getImageArtifact(string $artifact): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $artifact | Точное имя внутреннего artifact ImageMagick.Точная формулировка PHP ManualThe name of the artifact |
Возврат и видимый итог. Возвращается строковое значение управляющего параметра.
Соседний выбор. getOption() для объектной option.
Точные соседние карточки. Imagick::setImageArtifact · Imagick::deleteImageArtifact.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageArtifact('compose:args', '20x20');
$result = $image->getImageArtifact('compose:args');
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImageArtifact',
'returned' => aenObserve('Imagick::getImageArtifact', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается строковое значение управляющего параметра. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageArtifact('distort:viewport', '640x480+0+0');
$result = $image->getImageArtifact('distort:viewport');
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$viewport = $result;
$artifactIsExplicit = str_contains($viewport, 'x');
$observation = [
'method' => 'Imagick::getImageArtifact',
'returned' => aenObserve('Imagick::getImageArtifact', $result),
'effect' => aenObserve('Imagick::getImageArtifact:effect', $artifactIsExplicit),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается строковое значение управляющего параметра. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Get image artifact
Description: Gets an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. Available since Imagick 6.5.7.
Return: Returns the artifact value on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: Imagick::setImageArtifact, Imagick::deleteImageArtifact
Source hashes: page ead97c188da10a5aaa96b31d260d6a1ef5efc6a6a4359f681cc4a570c6410a69; XML 3beacc4c4f81d4850a1219ad67ddef885294a52f52cb9acfab322c84a06a0b8b.
Imagick::getImageBlobСтрока содержит бинарный кодированный image payload.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageBlob(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно получить байты одного текущего кадра без промежуточного файла
- Метод получает явно подготовленное состояние и параметры
- После вызова строка содержит бинарный кодированный image payload
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Получить байты одного текущего кадра без промежуточного файла.
Сигнатура. Imagick::getImageBlob(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Строка содержит бинарный кодированный image payload.
Соседний выбор. writeImageFile() для stream и больших результатов.
Точные соседние карточки. Imagick::__toString.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageBlob();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImageBlob',
'returned' => aenObserve('Imagick::getImageBlob', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: строка содержит бинарный кодированный image payload. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageBlob();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
if (!str_starts_with($result, 'P6')) { throw new \RuntimeException('Blob не содержит PPM'); }
$written = file_put_contents(__DIR__ . '/out/current-frame.ppm', $result, LOCK_EX);
if ($written !== strlen($result)) { throw new \RuntimeException('Blob записан не полностью'); }
$observation = [
'method' => 'Imagick::getImageBlob',
'returned' => aenObserve('Imagick::getImageBlob', $result),
'effect' => aenObserve('Imagick::getImageBlob:effect', $written),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: строка содержит бинарный кодированный image payload. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the image sequence as a blob
Description: Implements direct to memory image formats. It returns the image sequence as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().
Return: Returns a string containing the image.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 9da180a758f20900956a6971bcd0b6f3bf7eb8164d9fb55932ec19dfd117de4b; XML 6560c58f46c899ae1d01d5e4a8f53a5ac6607e05eef4425a562b9948499ad890.
Imagick::getImageFilenameВозвращается строковое имя конкретного image.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageFilename(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно узнать filename текущего кадра в последовательности
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается строковое имя конкретного image
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Узнать filename текущего кадра в последовательности.
Сигнатура. Imagick::getImageFilename(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Возвращается строковое имя конкретного image.
Соседний выбор. setImageFilename() для явной маркировки кадра.
Точные соседние карточки. Imagick::getFilename · Imagick::setFilename.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageFilename();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImageFilename',
'returned' => aenObserve('Imagick::getImageFilename', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается строковое имя конкретного image. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageFilename();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$logicalFrameName = basename($result);
$observation = [
'method' => 'Imagick::getImageFilename',
'returned' => aenObserve('Imagick::getImageFilename', $result),
'effect' => aenObserve('Imagick::getImageFilename:effect', $logicalFrameName),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается строковое имя конкретного image. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the filename of a particular image in a sequence
Description: Returns the filename of a particular image in a sequence.
Return: Returns a string with the filename of the image.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 0790d79d3957d30e044b238e56908c3b773aacc551e8e9ae7a4f288615d9b0d2; XML 8ddefa27f7b96cfefe5816a01b6d16e7a4c619ba53fcc86ead5dcf9f0caef354.
Imagick::getImageFormatВозвращается png, jpeg, gif и другое имя coder.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageFormat(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно проверить decoder/encoder format текущего кадра
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается PNG, JPEG, GIF и другое имя coder
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Проверить decoder/encoder format текущего кадра.
Сигнатура. Imagick::getImageFormat(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Возвращается png, jpeg, gif и другое имя coder.
Соседний выбор. getImageMimeType() плюс queryFormats().
Точные соседние карточки. Imagick::getFormat · Imagick::getImageMimeType.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageFormat();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImageFormat',
'returned' => aenObserve('Imagick::getImageFormat', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается PNG, JPEG, GIF и другое имя coder. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageFormat();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$actualFormat = strtoupper($result);
if ($actualFormat !== 'PPM') { throw new \RuntimeException('Контрольный PPM распознан как другой формат'); }
$observation = [
'method' => 'Imagick::getImageFormat',
'returned' => aenObserve('Imagick::getImageFormat', $result),
'effect' => aenObserve('Imagick::getImageFormat:effect', $actualFormat),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается PNG, JPEG, GIF и другое имя coder. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the format of a particular image in a sequence
Description: Returns the format of a particular image in a sequence.
Return: Returns a string containing the image format on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 35b396f23bb5c2df724d2d86b78348128a6818c5a7b4843cce829389592f938b; XML b6b790423038cca09159add9e760a3da388436f1a426b0c5c81220ac5bf2dcfd.
Imagick::getImageMimeTypeВозвращается строка вроде image/png.
PECL imagick 2 >= 2.3.0, PECL imagick 3 · imagick
Imagick::getImageMimeType(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно получить MIME-подсказку из фактического image format
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается строка вроде image/png
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Получить mime-подсказку из фактического image format.
Сигнатура. Imagick::getImageMimeType(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Возвращается строка вроде image/png.
Соседний выбор. finfo для исходного файла и getImageFormat() для decoder.
Точные соседние карточки. Imagick::getFormat · Imagick::getImageFormat.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageMimeType();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImageMimeType',
'returned' => aenObserve('Imagick::getImageMimeType', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается строка вроде image/png. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImageMimeType();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$mime = strtolower($result);
if (!in_array($mime, ['image/x-portable-pixmap', 'image/x-portable-anymap'], true)) { throw new \RuntimeException('MIME fixture не соответствует PPM'); }
$observation = [
'method' => 'Imagick::getImageMimeType',
'returned' => aenObserve('Imagick::getImageMimeType', $result),
'effect' => aenObserve('Imagick::getImageMimeType:effect', $mime),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается строка вроде image/png. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2 >= 2.3.0, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the image mime-type
Description: Returns the image mime-type.
Return: Not stated on the source page.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 2d16fe995364b2233c439ba192eb89ccfecc518a91bac1d86de5e3f4b41ef205; XML 73ffa9dec2760a3e3d51a6faa00f675862754fe37a1974ad0e111725218b8882.
Imagick::getImageProfileВозвращается бинарная строка выбранного профиля.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageProfile(string $name): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно извлечь один бинарный ICC/IPTC/EXIF profile перед контролируемым удалением
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается бинарная строка выбранного профиля
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Извлечь один бинарный icc/iptc/exif profile перед контролируемым удалением.
Сигнатура. Imagick::getImageProfile(string $name): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка.Точная формулировка PHP ManualThe name of the profile to return. |
Возврат и видимый итог. Возвращается бинарная строка выбранного профиля.
Соседний выбор. getImageProfiles() для безопасной проверки наличия.
Точные соседние карточки. Imagick::getImageProfiles · Imagick::profileImage.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$seedProfile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($seedProfile === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $seedProfile);
$result = $image->getImageProfile('xmp');
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImageProfile',
'returned' => aenObserve('Imagick::getImageProfile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается бинарная строка выбранного профиля. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$seedProfile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($seedProfile === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $seedProfile);
$result = $image->getImageProfile('xmp');
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$xmpBytes = strlen($result);
if ($xmpBytes === 0 || $xmpBytes > 1_000_000) { throw new \RuntimeException('XMP profile пуст или слишком велик'); }
$observation = [
'method' => 'Imagick::getImageProfile',
'returned' => aenObserve('Imagick::getImageProfile', $result),
'effect' => aenObserve('Imagick::getImageProfile:effect', $xmpBytes),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается бинарная строка выбранного профиля. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the named image profile
Description: Returns the named image profile.
Return: Returns a string containing the image profile.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page ee3c6e70b8bd5139ba15b32925605250210525010f6ec06160220c767fcd84b5; XML 4d141efd29a6f8c0121f49901d538f925b48d2602c8122a6d2c6dba9c783dd11.
Imagick::getImageProfilesМассив содержит имена либо name=>blob по include_values.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageProfiles(string $pattern = "*", bool $include_values = true): arrayПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно перечислить профили кадра или получить их бинарные значения
- Метод получает явно подготовленное состояние и параметры
- После вызова массив содержит имена либо name=>blob по include_values
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Перечислить профили кадра или получить их бинарные значения.
Сигнатура. Imagick::getImageProfiles(string $pattern = "*", bool $include_values = true): array
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $pattern = "*" | Ограниченный glob-pattern для имён, а не путь к файлам.Точная формулировка PHP ManualThe pattern for profile names. |
bool $include_values = true | false возвращает только имена и экономит память; true добавляет значения.Точная формулировка PHP ManualWhether to return only profile names. If false then only profile names will be returned. |
Возврат и видимый итог. Массив содержит имена либо name=>blob по include_values.
Соседний выбор. include_values=false для инвентаризации.
Точные соседние карточки. Imagick::getImageProfile · Imagick::profileImage.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$seedProfile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($seedProfile === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $seedProfile);
$result = $image->getImageProfiles('*', false);
$resultCount = count($result);
$observation = [
'method' => 'Imagick::getImageProfiles',
'returned' => aenObserve('Imagick::getImageProfiles:names', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: массив содержит имена либо name=>blob по include_values. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$seedProfile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($seedProfile === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $seedProfile);
$result = $image->getImageProfiles('xmp', true);
$resultCount = count($result);
$xmp = $result['xmp'] ?? null;
if (!is_string($xmp)) { throw new \RuntimeException('XMP profile отсутствует'); }
$observation = [
'method' => 'Imagick::getImageProfiles',
'returned' => aenObserve('Imagick::getImageProfiles', $result),
'effect' => aenObserve('Imagick::getImageProfiles:effect', $xmp),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: массив содержит имена либо name=>blob по include_values. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the image profiles
Description: Returns all associated profiles that match the pattern. If false is passed as second parameter only the profile names are returned. Available since Imagick 6.3.6.
Return: Returns an array containing the image profiles or profile names.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page fdaa01adc02f7a4bb19870b43f271239a259150492ead39fdf4e08298b496211; XML a09a1b7a154fc5e5c9bd8729bc7c972b0375264aa966e513526aee24af23ace4.
Imagick::getImagePropertiesМассив возвращает имена или name=>value.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageProperties(string $pattern = "*", bool $include_values = true): arrayПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно найти свойства кадра по pattern для диагностики метаданных
- Метод получает явно подготовленное состояние и параметры
- После вызова массив возвращает имена или name=>value
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Найти свойства кадра по pattern для диагностики метаданных.
Сигнатура. Imagick::getImageProperties(string $pattern = "*", bool $include_values = true): array
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $pattern = "*" | Ограниченный glob-pattern для имён, а не путь к файлам.Точная формулировка PHP ManualThe pattern for property names. |
bool $include_values = true | false возвращает только имена и экономит память; true добавляет значения.Точная формулировка PHP ManualWhether to return only property names. If false then only property names will be returned. |
Возврат и видимый итог. Массив возвращает имена или name=>value.
Соседний выбор. getImageProperty() по разрешённому точному имени.
Точные соседние карточки. Imagick::deleteImageProperty · Imagick::getImageProperty.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageProperty('exif:DateTimeOriginal', '2026:10:16 12:00:00');
$result = $image->getImageProperties('exif:*', false);
$resultCount = count($result);
$observation = [
'method' => 'Imagick::getImageProperties',
'returned' => aenObserve('Imagick::getImageProperties', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: массив возвращает имена или name=>value. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageProperty('icc:model', 'sRGB IEC61966-2.1');
$result = $image->getImageProperties('icc:*', true);
$resultCount = count($result);
$colorModel = $result['icc:model'] ?? 'unknown';
$observation = [
'method' => 'Imagick::getImageProperties',
'returned' => aenObserve('Imagick::getImageProperties', $result),
'effect' => aenObserve('Imagick::getImageProperties:effect', $colorModel),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: массив возвращает имена или name=>value. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the image properties
Description: Returns all associated properties that match the pattern. If false is passed as second parameter only the property names are returned. Available since Imagick 6.3.6.
Return: Returns an array containing the image properties or property names.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 39d36486906f789550b6d803d7a351b031bd22a3585970985b234ea49bf1a10c; XML 266fe935fe00df5102463f67c4261088e609de2403708b86e756cb71124775da.
Imagick::getImagePropertyВозвращается строка property value.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImageProperty(string $name): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно прочитать одно разрешённое свойство изображения
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается строка property value
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Прочитать одно разрешённое свойство изображения.
Сигнатура. Imagick::getImageProperty(string $name): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка.Точная формулировка PHP Manualname of the property (for example Exif:DateTime) |
Возврат и видимый итог. Возвращается строка property value.
Соседний выбор. getImageProperties() для ограниченного pattern.
Точные соседние карточки. Imagick::setImageProperty.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
if ($image->setImageProperty('exif:DateTimeOriginal', '2026:10:16 12:00:00') !== true) { throw new \RuntimeException('Не удалось задать контрольное свойство'); }
$result = $image->getImageProperty('exif:DateTimeOriginal');
if ($result === false || $result === '') { throw new \RuntimeException('Запрошенное значение не установлено'); }
$observation = [
'method' => 'Imagick::getImageProperty',
'returned' => aenObserve('Imagick::getImageProperty', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается строка property value. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
if ($image->setImageProperty('icc:model', 'sRGB IEC61966-2.1') !== true) { throw new \RuntimeException('Не удалось задать контрольное свойство'); }
$result = $image->getImageProperty('icc:model');
if ($result === false || $result === '') { throw new \RuntimeException('Запрошенное значение не установлено'); }
$iccModel = $result;
$hasNamedProfile = $iccModel !== false && $iccModel !== '';
if (!$hasNamedProfile) { throw new \RuntimeException('Контрольное свойство отсутствует'); }
$observation = [
'method' => 'Imagick::getImageProperty',
'returned' => aenObserve('Imagick::getImageProperty', $result),
'effect' => aenObserve('Imagick::getImageProperty:effect', $hasNamedProfile),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается строка property value. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the named image property
Description: Returns the named image property. Available since Imagick 6.3.2.
Return: Returns a string containing the image property, false if a property with the given name does not exist.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::setImageProperty
Source hashes: page 16b3c5d04d3e75e62bc7a3fd1d6223def5dc48898343b7ebefc210ec054faf45; XML 5b0f39de4d014ce2d24d8eda06ef6e73ad0ab9f0bfa07aa135f9d37f0ecb7102.
Imagick::getImagesBlobСтрока содержит multiframe gif/tiff/pdf либо объединённый output coder.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::getImagesBlob(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно получить байты всей последовательности кадров
- Метод получает явно подготовленное состояние и параметры
- После вызова строка содержит multiframe GIF/TIFF/PDF либо объединённый output coder
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Получить байты всей последовательности кадров.
Сигнатура. Imagick::getImagesBlob(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Строка содержит multiframe gif/tiff/pdf либо объединённый output coder.
Соседний выбор. writeImagesFile() для stream.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->getImagesBlob();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::getImagesBlob',
'returned' => aenObserve('Imagick::getImagesBlob', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: строка содержит multiframe GIF/TIFF/PDF либо объединённый output coder. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->readImage(__DIR__ . '/fixtures/back.ppm');
foreach ($image as $frame) {
$frame->setImageFormat('gif');
}
$image->setFirstIterator();
$result = $image->getImagesBlob();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$signature = substr($result, 0, 6);
if (!in_array($signature, ['GIF87a', 'GIF89a'], true)) { throw new \RuntimeException('getImagesBlob() вернул не GIF'); }
$written = file_put_contents(__DIR__ . '/out/animation.gif', $result, LOCK_EX);
if ($written !== strlen($result)) { throw new \RuntimeException('Sequence blob записан не полностью'); }
$observation = [
'method' => 'Imagick::getImagesBlob',
'returned' => aenObserve('Imagick::getImagesBlob', $result),
'effect' => aenObserve('Imagick::getImagesBlob:effect', $written),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: строка содержит multiframe GIF/TIFF/PDF либо объединённый output coder. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns all image sequences as a blob
Description: Implements direct to memory image formats. It returns all image sequences as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().
Return: Returns a string containing the images. On failure, throws ImagickException.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 858faa2059dbaa39b0b378509ab508348efce749721b6a699290f1c6b4cad7f9; XML e426a9984422f8f6af39ffcfc3ac262a1ae487c6c175e2e77d47b4917dc8242e.
Imagick::identifyFormatВозвращается строка по escape-шаблону imagemagick либо false.
PECL imagick 3 >= 3.3.0 · imagick
Imagick::identifyFormat(string $embedText): string|falseПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно сформировать короткую диагностическую строку из properties без ручной склейки
- Метод получает явно подготовленное состояние и параметры
- После вызова возвращается строка по escape-шаблону ImageMagick либо false
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Сформировать короткую диагностическую строку из properties без ручной склейки.
Сигнатура. Imagick::identifyFormat(string $embedText): string|false
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $embedText | Шаблон ImageMagick identify escapes, например '%m %wx%h'.Точная формулировка PHP ManualA string containing formatting sequences e.g. "Trim box: %@ number of unique colors: %k". |
Возврат и видимый итог. Возвращается строка по escape-шаблону imagemagick либо false.
Соседний выбор. identifyImage() для структурированного массива.
Точные соседние карточки. Imagick::identifyImage.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->identifyFormat('%m %wx%h');
if ($result === false) { throw new \RuntimeException('Imagick не сформировал результат'); }
$observation = [
'method' => 'Imagick::identifyFormat',
'returned' => aenObserve('Imagick::identifyFormat', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: возвращается строка по escape-шаблону ImageMagick либо false. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->identifyFormat('%m %[channels] %b');
if ($result === false) { throw new \RuntimeException('Imagick не сформировал результат'); }
$parts = preg_split('/\s+/', trim($result));
if ($parts === false || count($parts) < 3) { throw new \RuntimeException('Identify template дал неожиданный результат'); }
$observation = [
'method' => 'Imagick::identifyFormat',
'returned' => aenObserve('Imagick::identifyFormat', $result),
'effect' => aenObserve('Imagick::identifyFormat:effect', $parts),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: возвращается строка по escape-шаблону ImageMagick либо false. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 3 >= 3.3.0 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Formats a string with image details
Description: Replaces any embedded formatting characters with the appropriate image property and returns the interpreted text. See http://www.imagemagick.org/script/escape.php for escape sequences.
Return: Returns format[return.falseforfailure].
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page ca55fcbeee4e7f5ba0d340f687a4367b6327b80fbc5ccb7a03814e73c2e6a724; XML a415d2eab2217c585fdf9ccbe89f37abedfa9da63293b1d375f18da6e83b2fd3.
Imagick::identifyImageМассив содержит format, geometry, resolution, filesize и другие поля.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::identifyImage(bool $appendRawOutput = false): arrayПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
Что делает именно этот метод. Получить структурированную диагностику текущего кадра.
Сигнатура. Imagick::identifyImage(bool $appendRawOutput = false): array
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
bool $appendRawOutput = false | true добавляет сырой диагностический output и увеличивает объём массива.Точная формулировка PHP ManualIf true then the raw output is appended to the array. |
Возврат и видимый итог. Массив содержит format, geometry, resolution, filesize и другие поля.
Соседний выбор. точечные getters для контрактных данных.
Точные соседние карточки. Imagick::identifyFormat.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->identifyImage(false);
$resultCount = count($result);
$observation = [
'method' => 'Imagick::identifyImage',
'returned' => aenObserve('Imagick::identifyImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: массив содержит format, geometry, resolution, filesize и другие поля. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->identifyImage(true);
$resultCount = count($result);
$geometry = $result['geometry'] ?? null;
if (!is_array($geometry)) { throw new \RuntimeException('Identify не вернул geometry'); }
$observation = [
'method' => 'Imagick::identifyImage',
'returned' => aenObserve('Imagick::identifyImage', $result),
'effect' => aenObserve('Imagick::identifyImage:effect', $geometry),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: массив содержит format, geometry, resolution, filesize и другие поля. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Identifies an image and fetches attributes
Description: Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.
Return: Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 06717647a6a56829b3e6977adc9ef1161d7c9f0fa9869ed9037cbb8b7fead805; XML 723e259a797650ed91ad0ec1d7f32c2d1b7258e4eae4fbed28d4c3d722644f37.
Imagick::labelImageПоддерживающий coder сохраняет label metadata.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::labelImage(string $label): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно назначить label текущему кадру, например подпись страницы
- Метод получает явно подготовленное состояние и параметры
- После вызова поддерживающий coder сохраняет label metadata
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Назначить label текущему кадру, например подпись страницы.
Сигнатура. Imagick::labelImage(string $label): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $label | Короткая подпись metadata; она не рисуется на изображении.Точная формулировка PHP ManualThe label to add |
Возврат и видимый итог. Поддерживающий coder сохраняет label metadata.
Соседний выбор. annotateImage() для видимого текста.
Точные соседние карточки. Imagick::commentImage.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->labelImage('page-1');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::labelImage',
'returned' => aenObserve('Imagick::labelImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: поддерживающий coder сохраняет label metadata. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->labelImage('order-42-preview');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$storedLabel = $image->getImageProperty('label');
$observation = [
'method' => 'Imagick::labelImage',
'returned' => aenObserve('Imagick::labelImage', $result),
'effect' => aenObserve('Imagick::labelImage:effect', $storedLabel),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: поддерживающий coder сохраняет label metadata. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Adds a label to an image
Description: Adds a label to an image.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 88c6e10c9dd259bf751c227ec5a36883b6e12a3b9b782d0ffebe500436c933f0; XML 5c41d6a0088369ba53d850a1d6257ee0857138f5f502676107cd6708b6bf76fd.
Imagick::pingImageОбъект получает базовые атрибуты с меньшей стоимостью, чем readimage().
PECL imagick 2, PECL imagick 3 · imagick
Imagick::pingImage(string $filename): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно узнать формат и размеры локального файла до полного декодирования
- Метод получает явно подготовленное состояние и параметры
- После вызова объект получает базовые атрибуты с меньшей стоимостью, чем readImage()
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Узнать формат и размеры локального файла до полного декодирования.
Сигнатура. Imagick::pingImage(string $filename): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $filename | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога.Точная формулировка PHP ManualThe filename to read the information from. |
Возврат и видимый итог. Объект получает базовые атрибуты с меньшей стоимостью, чем readimage().
Соседний выбор. readImage() после allowlist и resource policy.
Точные соседние карточки. Imagick::pingImageBlob.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$result = $image->pingImage(__DIR__ . '/fixtures/product.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::pingImage',
'returned' => aenObserve('Imagick::pingImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: объект получает базовые атрибуты с меньшей стоимостью, чем readImage(). Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$result = $image->pingImage(__DIR__ . '/fixtures/back.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$geometry = $image->getImageGeometry();
if (($geometry['width'] ?? 0) * ($geometry['height'] ?? 0) > 40_000_000) { throw new \RuntimeException('Каталог содержит слишком большой raster'); }
$observation = [
'method' => 'Imagick::pingImage',
'returned' => aenObserve('Imagick::pingImage', $result),
'effect' => aenObserve('Imagick::pingImage:effect', $geometry),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: объект получает базовые атрибуты с меньшей стоимостью, чем readImage(). Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Fetch basic attributes about the image
Description: This method can be used to query image width, height, size, and format without reading the whole image in to memory.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 1eb0658db20f45f2525b0dea7f843292d8a4dbadd877e973a64aaf64ab03f0b0; XML db4b7e46d9df524caeca10a6b77823d34ebfac94ddde3a29623c4a9ad46fd86e.
Imagick::pingImageBlobДоступны базовые format/geometry attributes.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::pingImageBlob(string $image): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно предварительно проверить загруженные бинарные bytes без сохранения постоянного файла
- Метод получает явно подготовленное состояние и параметры
- После вызова доступны базовые format/geometry attributes
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Предварительно проверить загруженные бинарные bytes без сохранения постоянного файла.
Сигнатура. Imagick::pingImageBlob(string $image): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $image | Бинарные bytes изображения, ограниченные по размеру до вызова.Точная формулировка PHP ManualA string containing the image. |
Возврат и видимый итог. Доступны базовые format/geometry attributes.
Соседний выбор. tmpfile()+pingImageFile() для stream.
Точные соседние карточки. Imagick::pingImage · Imagick::pingImageFile · Imagick::readImage · Imagick::readImageBlob.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$blob = file_get_contents(__DIR__ . '/fixtures/product.ppm');
if ($blob === false || strlen($blob) > 8_000_000) {
throw new \RuntimeException('Не удалось получить ограниченный image payload');
}
$result = $image->pingImageBlob($blob);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::pingImageBlob',
'returned' => aenObserve('Imagick::pingImageBlob', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: доступны базовые format/geometry attributes. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$uploadBytes = file_get_contents(__DIR__ . '/fixtures/back.ppm');
if ($uploadBytes === false || strlen($uploadBytes) > 8_000_000) {
throw new \RuntimeException('Не удалось получить ограниченный image payload');
}
$result = $image->pingImageBlob($uploadBytes);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$geometry = $image->getImageGeometry();
$acceptedUploadHeader = ($geometry['width'] ?? 0) <= 8000 && ($geometry['height'] ?? 0) <= 8000;
$observation = [
'method' => 'Imagick::pingImageBlob',
'returned' => aenObserve('Imagick::pingImageBlob', $result),
'effect' => aenObserve('Imagick::pingImageBlob:effect', $acceptedUploadHeader),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: доступны базовые format/geometry attributes. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Quickly fetch attributes
Description: This method can be used to query image width, height, size, and format without reading the whole image to memory. Available since Imagick 6.2.9.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::pingImage, Imagick::pingImageFile, Imagick::readImage, Imagick::readImageBlob, Imagick::readImageFile
Source hashes: page 90642265079e0c13f41114dd5f2a6e7838dc3392070a036914fb747413ecbd8c; XML 799701aa2f40bceb0b442289a5f93ab97cd3a4b9f707aecf43721b9b02ed9793.
Imagick::pingImageFileПолучаются базовые атрибуты без полного pixel decode.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::pingImageFile(resource $filehandle, string $fileName = ?): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно прочитать заголовок image из seekable file handle
- Метод получает явно подготовленное состояние и параметры
- После вызова получаются базовые атрибуты без полного pixel decode
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Прочитать заголовок image из seekable file handle.
Сигнатура. Imagick::pingImageFile(resource $filehandle, string $fileName = ?): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
resource $filehandle | Проверенный открытый binary stream в нужном режиме и позиции.Точная формулировка PHP ManualAn open filehandle to the image. |
string $fileName = значение по умолчанию | Необязательное логическое имя с расширением для подсказки coder.Точная формулировка PHP ManualOptional filename for this image. |
Возврат и видимый итог. Получаются базовые атрибуты без полного pixel decode.
Соседний выбор. pingImage() для локального пути.
Точные соседние карточки. Imagick::pingImage · Imagick::pingImageBlob · Imagick::readImage · Imagick::readImageBlob.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$handle = fopen(__DIR__ . '/fixtures/product.ppm', 'rb');
if ($handle === false) { throw new \RuntimeException('Не открыт input stream'); }
rewind($handle);
$result = $image->pingImageFile($handle, 'product.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::pingImageFile',
'returned' => aenObserve('Imagick::pingImageFile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: получаются базовые атрибуты без полного pixel decode. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$handle = fopen(__DIR__ . '/fixtures/back.ppm', 'rb');
if ($handle === false) { throw new \RuntimeException('Не открыт input stream'); }
rewind($handle);
$result = $image->pingImageFile($handle, 'back.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$geometry = $image->getImageGeometry();
$acceptedStreamHeader = ($geometry['width'] ?? 0) * ($geometry['height'] ?? 0) <= 40_000_000;
$observation = [
'method' => 'Imagick::pingImageFile',
'returned' => aenObserve('Imagick::pingImageFile', $result),
'effect' => aenObserve('Imagick::pingImageFile:effect', $acceptedStreamHeader),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: получаются базовые атрибуты без полного pixel decode. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Get basic image attributes in a lightweight manner
Description: This method can be used to query image width, height, size, and format without reading the whole image to memory. Available since Imagick 6.2.9.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::pingImage, Imagick::pingImageBlob, Imagick::readImage, Imagick::readImageBlob, Imagick::readImageFile
Source hashes: page d0336ced6084d8ceb08a2e397c5a5b0845abf012ad7eda1bb82beef98c3af5b1; XML 39361860ca0f9642cb7c34f4c7df8bda33b171e27274114cdb60631dbdea99f3.
Imagick::profileImageПрофиль влияет на цветовое преобразование либо метаданные кадра.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::profileImage(string $name, string $profile = ?): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно добавить, заменить или удалить ICC/IPTC/generic profile
- Метод получает явно подготовленное состояние и параметры
- После вызова профиль влияет на цветовое преобразование либо метаданные кадра
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Добавить, заменить или удалить icc/iptc/generic profile.
Сигнатура. Imagick::profileImage(string $name, string $profile = ?): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка.Точная формулировка PHP ManualThe profile name. |
string $profile = значение по умолчанию | Бинарные данные доверенного профиля; null в profileImage удаляет профиль.Точная формулировка PHP ManualThe profile data. If null, the specified profile will be deleted. |
Возврат и видимый итог. Профиль влияет на цветовое преобразование либо метаданные кадра.
Соседний выбор. setImageProfile() для назначения raw profile без общего profile operation.
Точные соседние карточки. Imagick::getImageProfile · Imagick::getImageProfiles.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$profile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($profile === false || strlen($profile) > 1_000_000) {
throw new \RuntimeException('Не прочитан ограниченный XMP profile');
}
$result = $image->profileImage('xmp', $profile);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::profileImage',
'returned' => aenObserve('Imagick::profileImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: профиль влияет на цветовое преобразование либо метаданные кадра. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$profile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($profile === false || strlen($profile) > 1_000_000) {
throw new \RuntimeException('Не прочитан ограниченный XMP profile');
}
if ($image->setImageProfile('xmp', $profile) !== true) { throw new \RuntimeException('Не удалось прикрепить XMP перед удалением'); }
$profilesBeforeRemoval = $image->getImageProfiles('*', false);
if (!in_array('xmp', $profilesBeforeRemoval, true)) { throw new \RuntimeException('Контрольный XMP не появился до profileImage(..., null)'); }
$result = $image->profileImage('xmp', null);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$remainingProfiles = $image->getImageProfiles('*', false);
$xmpRemoved = !in_array('xmp', $remainingProfiles, true);
if (!$xmpRemoved) { throw new \RuntimeException('XMP profile не удалён'); }
$observation = [
'method' => 'Imagick::profileImage',
'returned' => aenObserve('Imagick::profileImage', $result),
'effect' => aenObserve('Imagick::profileImage:effect', $xmpRemoved),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: профиль влияет на цветовое преобразование либо метаданные кадра. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Adds or removes a profile from an image
Description: Adds or removes a ICC , IPTC , or generic profile from an image. If the profile is null, it is removed from the image rather than added. To remove every single profile from the image use '*' as the name and null for the profile .
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page b47a58781c1dc87d0f82d742d7eb77937fcd245034b62aaa67a5d4edea77f1f8; XML 45a2251649fad33cb2ad1fb31c2d467b23c2d7afab642350c4e04b9bf17b53a2.
Imagick::readImageОбъект содержит декодированные пиксели и кадры.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::readImage(string $filename): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно полностью прочитать доверенный локальный файл или выбранную страницу
- Метод получает явно подготовленное состояние и параметры
- После вызова объект содержит декодированные пиксели и кадры
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Полностью прочитать доверенный локальный файл или выбранную страницу.
Сигнатура. Imagick::readImage(string $filename): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $filename | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога. |
Возврат и видимый итог. Объект содержит декодированные пиксели и кадры.
Соседний выбор. readImageFile() для уже открытого handle.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$result = $image->readImage(__DIR__ . '/fixtures/product.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::readImage',
'returned' => aenObserve('Imagick::readImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: объект содержит декодированные пиксели и кадры. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->setResolution(144.0, 144.0);
$result = $image->readImage(__DIR__ . '/fixtures/vector.svg');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$loadedFrames = $image->getNumberImages();
if ($loadedFrames !== 1) { throw new \RuntimeException('Для preview нужен один SVG-кадр'); }
$observation = [
'method' => 'Imagick::readImage',
'returned' => aenObserve('Imagick::readImage', $result),
'effect' => aenObserve('Imagick::readImage:effect', $loadedFrames),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: объект содержит декодированные пиксели и кадры. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Reads image from filename
Description: Reads image from filename
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page f113f974b7590d6ca94caa1ab9f2255db55e7641e1ddf1c106bef72992925723; XML b5bd610ebeef4e8d323b0524c72d35d7b119232e999e13e3b9d145e74b6c224f.
Imagick::readImageBlobОбъект содержит изображение из bytes; optional filename помогает coder определить контекст.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::readImageBlob(string $image, string $filename = ?): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно декодировать бинарную строку, уже полученную приложением
- Метод получает явно подготовленное состояние и параметры
- После вызова объект содержит изображение из bytes; optional filename помогает coder определить контекст
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Декодировать бинарную строку, уже полученную приложением.
Сигнатура. Imagick::readImageBlob(string $image, string $filename = ?): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $image | Бинарные bytes изображения, ограниченные по размеру до вызова. |
string $filename = значение по умолчанию | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога. |
Возврат и видимый итог. Объект содержит изображение из bytes; optional filename помогает coder определить контекст.
Соседний выбор. readImageFile() через bounded temporary stream.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$blob = file_get_contents(__DIR__ . '/fixtures/product.ppm');
if ($blob === false || strlen($blob) > 8_000_000) {
throw new \RuntimeException('Не удалось получить ограниченный image payload');
}
$result = $image->readImageBlob($blob, 'product.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::readImageBlob',
'returned' => aenObserve('Imagick::readImageBlob', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: объект содержит изображение из bytes; optional filename помогает coder определить контекст. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$uploadBytes = file_get_contents(__DIR__ . '/fixtures/back.ppm');
if ($uploadBytes === false || strlen($uploadBytes) > 8_000_000) {
throw new \RuntimeException('Не удалось получить ограниченный image payload');
}
$result = $image->readImageBlob($uploadBytes, 'back.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$actualFormat = $image->getImageFormat();
if (strtoupper($actualFormat) !== 'PPM') { throw new \RuntimeException('Payload fixture не является PPM'); }
$observation = [
'method' => 'Imagick::readImageBlob',
'returned' => aenObserve('Imagick::readImageBlob', $result),
'effect' => aenObserve('Imagick::readImageBlob:effect', $actualFormat),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: объект содержит изображение из bytes; optional filename помогает coder определить контекст. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Reads image from a binary string
Description: Reads image from a binary string
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 8a55bf53d4c4c758928ac7f3656524f8e37768c15d277bb6a74ae8390ceb144b; XML a8bb6448b3dfd74d26af32a8bdfcef81874134498cca3c57ece9cdea85b53fbf.
Imagick::readImageFileОбъект получает кадры из текущей позиции handle.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::readImageFile(resource $filehandle, string $fileName = null): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно прочитать image из проверенного PHP stream
- Метод получает явно подготовленное состояние и параметры
- После вызова объект получает кадры из текущей позиции handle
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Прочитать image из проверенного php stream.
Сигнатура. Imagick::readImageFile(resource $filehandle, string $fileName = null): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
resource $filehandle | Проверенный открытый binary stream в нужном режиме и позиции. |
string $fileName = null | Необязательное логическое имя с расширением для подсказки coder. |
Возврат и видимый итог. Объект получает кадры из текущей позиции handle.
Соседний выбор. локальный временный файл и readImage().
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$handle = fopen(__DIR__ . '/fixtures/product.ppm', 'rb');
if ($handle === false) { throw new \RuntimeException('Не открыт input stream'); }
rewind($handle);
$result = $image->readImageFile($handle, 'product.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::readImageFile',
'returned' => aenObserve('Imagick::readImageFile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: объект получает кадры из текущей позиции handle. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$handle = fopen(__DIR__ . '/fixtures/back.ppm', 'rb');
if ($handle === false) { throw new \RuntimeException('Не открыт input stream'); }
rewind($handle);
$result = $image->readImageFile($handle, 'back.ppm');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$actualFormat = $image->getImageFormat();
$streamAccepted = strtoupper($actualFormat) === 'PPM';
if (!$streamAccepted) { throw new \RuntimeException('Stream fixture не является PPM'); }
$observation = [
'method' => 'Imagick::readImageFile',
'returned' => aenObserve('Imagick::readImageFile', $result),
'effect' => aenObserve('Imagick::readImageFile:effect', $streamAccepted),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: объект получает кадры из текущей позиции handle. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Reads image from open filehandle
Description: Reads image from open filehandle
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 22387099d434a659f40fb1e5097a54752637bb91e0da1ee635373d3bf91cb37c; XML bcfd9cc987dfeb5bb36a350691630013f639916e459fb2151450f853285c0cad.
Imagick::readimagesОбъект получает кадры в переданном порядке.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::readImages(array $filenames): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно загрузить несколько явных локальных файлов в одну последовательность
- Метод получает явно подготовленное состояние и параметры
- После вызова объект получает кадры в переданном порядке
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Загрузить несколько явных локальных файлов в одну последовательность.
Сигнатура. Imagick::readImages(array $filenames): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
array $filenames | Явный ограниченный массив локальных путей в нужном порядке. |
Возврат и видимый итог. Объект получает кадры в переданном порядке.
Соседний выбор. цикл readImage() с пофайловой диагностикой.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$result = $image->readimages([__DIR__ . '/fixtures/front.ppm', __DIR__ . '/fixtures/back.ppm']);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::readimages',
'returned' => aenObserve('Imagick::readimages', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: объект получает кадры в переданном порядке. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$result = $image->readimages([__DIR__ . '/fixtures/page-1.ppm', __DIR__ . '/fixtures/page-2.ppm']);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$loadedFrames = $image->getNumberImages();
if ($loadedFrames !== 2) { throw new \RuntimeException('Не все страницы прочитаны'); }
$observation = [
'method' => 'Imagick::readimages',
'returned' => aenObserve('Imagick::readimages', $result),
'effect' => aenObserve('Imagick::readimages:effect', $loadedFrames),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: объект получает кадры в переданном порядке. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Reads image from an array of filenames
Description: Reads image from an array of filenames. All the images are held in a single Imagick object.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 1840173dff15fe088283c6fef52a27f8cbc52e050b85ba6c0462bacb77865a1e; XML 0c5ebe680e119e85aafb6766e1d1efbb30862d2e818476308c22bf9319e90d76.
Imagick::removeImageProfileМетод возвращает удалённый binary blob.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::removeImageProfile(string $name): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно извлечь и одновременно удалить один профиль
- Метод получает явно подготовленное состояние и параметры
- После вызова метод возвращает удалённый binary blob
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Извлечь и одновременно удалить один профиль.
Сигнатура. Imagick::removeImageProfile(string $name): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка. |
Возврат и видимый итог. Метод возвращает удалённый binary blob.
Соседний выбор. getImageProfile() затем profileImage(name, null) для явных шагов.
Точные соседние карточки. Imagick::getImageProfile · Imagick::getImageProfiles.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$seedProfile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($seedProfile === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $seedProfile);
$result = $image->removeImageProfile('xmp');
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::removeImageProfile',
'returned' => aenObserve('Imagick::removeImageProfile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: метод возвращает удалённый binary blob. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$seedProfile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($seedProfile === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $seedProfile);
$result = $image->removeImageProfile('xmp');
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$archivedXmp = $result;
$xmpRemoved = !in_array('xmp', $image->getImageProfiles('*', false), true);
$observation = [
'method' => 'Imagick::removeImageProfile',
'returned' => aenObserve('Imagick::removeImageProfile', $result),
'effect' => aenObserve('Imagick::removeImageProfile:effect', $xmpRemoved),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: метод возвращает удалённый binary blob. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Removes the named image profile and returns it
Description: Removes the named image profile and returns it.
Return: Returns a string containing the profile of the image.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 1ab6ad06171c1a9d7df7af4d7592dc1f16f507696b35eda350ce676df96b2efd; XML 12fae5b56d2dbfbd6d6be7f3b5866676d3f061aaf5e725cd3a0d5d50586ab7bb.
Imagick::setFilenameПоследующая операция без явного пути может использовать это имя.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::setFilename(string $filename): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно задать filename уровня wand перед чтением или записью
- Метод получает явно подготовленное состояние и параметры
- После вызова последующая операция без явного пути может использовать это имя
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Задать filename уровня wand перед чтением или записью.
Сигнатура. Imagick::setFilename(string $filename): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $filename | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога. |
Возврат и видимый итог. Последующая операция без явного пути может использовать это имя.
Соседний выбор. передавать явный filename в readImage()/writeImage().
Точные соседние карточки. Imagick::getFilename · Imagick::getImageFilename.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setFilename(__DIR__ . '/out/preview.png');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setFilename',
'returned' => aenObserve('Imagick::setFilename', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: последующая операция без явного пути может использовать это имя. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setFilename(__DIR__ . '/out/document.tiff');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$configuredObjectFilename = $image->getFilename();
$observation = [
'method' => 'Imagick::setFilename',
'returned' => aenObserve('Imagick::setFilename', $result),
'effect' => aenObserve('Imagick::setFilename:effect', $configuredObjectFilename),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: последующая операция без явного пути может использовать это имя. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Sets the filename before you read or write the image
Description: Sets the filename before you read or write an image file.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 583a4a783a5d44bd6f73b21e34e3e7d31ce4a1281435fa78e14cbda9193d5bdb; XML fa0ed9085e610a9fee20f114df39c09b5874f4905c83a12e4c1f9e5f06ec852a.
Imagick::setFormatObject format меняется для последующей blob/stream операции.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::setFormat(string $format): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно задать формат всего Imagick object/последовательности
- Метод получает явно подготовленное состояние и параметры
- После вызова object format меняется для последующей blob/stream операции
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Задать формат всего imagick object/последовательности.
Сигнатура. Imagick::setFormat(string $format): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $format | Имя coder вроде 'png' или 'jpeg', предварительно проверенное queryFormats(). |
Возврат и видимый итог. Object format меняется для последующей blob/stream операции.
Соседний выбор. setImageFormat() для image; writeImages() для sequence.
Точные соседние карточки. Imagick::getFormat · Imagick::getImageFormat.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setFormat('png');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setFormat',
'returned' => aenObserve('Imagick::setFormat', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: object format меняется для последующей blob/stream операции. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setFormat('gif');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$configuredObjectFormat = $image->getFormat();
$observation = [
'method' => 'Imagick::setFormat',
'returned' => aenObserve('Imagick::setFormat', $result),
'effect' => aenObserve('Imagick::setFormat:effect', $configuredObjectFormat),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: object format меняется для последующей blob/stream операции. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Sets the format of the Imagick object
Description: Sets the format of the Imagick object.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 6f3d374cd4ba8c79d499d38cefdc525d1bfca0a65c7ad6acf7c27d948a31d9be; XML d6a10465e33782504eb0b4d1a0a57b7a9d835f4c722f42fd4bc466d0dff158c6.
Imagick::setImageArtifactArtifact key влияет на следующую поддерживающую операцию.
PECL imagick 3 · imagick
Imagick::setImageArtifact(string $artifact, string $value): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно передать внутреннюю настройку encoder/effect конкретному кадру
- Метод получает явно подготовленное состояние и параметры
- После вызова artifact key влияет на следующую поддерживающую операцию
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Передать внутреннюю настройку encoder/effect конкретному кадру.
Сигнатура. Imagick::setImageArtifact(string $artifact, string $value): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $artifact | Точное имя внутреннего artifact ImageMagick.Точная формулировка PHP ManualThe name of the artifact |
string $value | Строковое значение текущей option/property/artifact/registry.Точная формулировка PHP ManualThe value of the artifact |
Возврат и видимый итог. Artifact key влияет на следующую поддерживающую операцию.
Соседний выбор. setOption() для wand-level define.
Точные соседние карточки. Imagick::getImageArtifact · Imagick::deleteImageArtifact.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageArtifact('compose:args', '20x20');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setImageArtifact',
'returned' => aenObserve('Imagick::setImageArtifact', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: artifact key влияет на следующую поддерживающую операцию. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageArtifact('distort:viewport', '640x480+0+0');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$configuredViewport = $image->getImageArtifact('distort:viewport');
$observation = [
'method' => 'Imagick::setImageArtifact',
'returned' => aenObserve('Imagick::setImageArtifact', $result),
'effect' => aenObserve('Imagick::setImageArtifact:effect', $configuredViewport),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: artifact key влияет на следующую поддерживающую операцию. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Set image artifact
Description: Associates an artifact with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. Available since Imagick 6.5.7.
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: Imagick::getImageArtifact, Imagick::deleteImageArtifact
Source hashes: page 4abc0f699ae1567ec9fe72a0a83f2086208f232053d71da70a0d059c771fbc34; XML 11014a9eb74533836ea0ed8d31ca5d4f7e4f0c37fa03098612da3e0346a3e730.
Imagick::setImageFilenameGetimagefilename() возвращает назначенную строку.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::setImageFilename(string $filename): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно дать текущему кадру явное логическое имя в sequence
- Метод получает явно подготовленное состояние и параметры
- После вызова getImageFilename() возвращает назначенную строку
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Дать текущему кадру явное логическое имя в sequence.
Сигнатура. Imagick::setImageFilename(string $filename): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $filename | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога. |
Возврат и видимый итог. Getimagefilename() возвращает назначенную строку.
Соседний выбор. writeImage($path) для физической записи.
Точные соседние карточки. Imagick::getFilename · Imagick::getImageFilename.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageFilename('product-preview.png');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setImageFilename',
'returned' => aenObserve('Imagick::setImageFilename', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: getImageFilename() возвращает назначенную строку. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageFilename('page-1.jpg');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$configuredFrameName = $image->getImageFilename();
$observation = [
'method' => 'Imagick::setImageFilename',
'returned' => aenObserve('Imagick::setImageFilename', $result),
'effect' => aenObserve('Imagick::setImageFilename:effect', $configuredFrameName),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: getImageFilename() возвращает назначенную строку. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Sets the filename of a particular image
Description: Sets the filename of a particular image in a sequence.
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page f5a8e47c4a7045be9d95889f0f144ae444a2a288f1da690f4705e43c86a62115; XML 801ac2bd74c3c743a5a72b6bdb65dca6e138d041c26e7fda0ba8232eb24e6759.
Imagick::setImageFormatСледующий getimageblob()/writeimage() создаёт указанный формат.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::setImageFormat(string $format): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно выбрать encoder format для текущего кадра
- Метод получает явно подготовленное состояние и параметры
- После вызова следующий getImageBlob()/writeImage() создаёт указанный формат
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Выбрать encoder format для текущего кадра.
Сигнатура. Imagick::setImageFormat(string $format): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $format | Имя coder вроде 'png' или 'jpeg', предварительно проверенное queryFormats().Точная формулировка PHP ManualString presentation of the image format. Format support depends on the ImageMagick installation. |
Возврат и видимый итог. Следующий getimageblob()/writeimage() создаёт указанный формат.
Соседний выбор. queryFormats() перед использованием и setFormat() для sequence.
Точные соседние карточки. Imagick::getFormat · Imagick::getImageFormat.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageFormat('png');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setImageFormat',
'returned' => aenObserve('Imagick::setImageFormat', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: следующий getImageBlob()/writeImage() создаёт указанный формат. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageFormat('webp');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$configuredFrameFormat = $image->getImageFormat();
if (strtoupper($configuredFrameFormat) !== 'WEBP') { throw new \RuntimeException('WEBP coder не выбран'); }
$observation = [
'method' => 'Imagick::setImageFormat',
'returned' => aenObserve('Imagick::setImageFormat', $result),
'effect' => aenObserve('Imagick::setImageFormat:effect', $configuredFrameFormat),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: следующий getImageBlob()/writeImage() создаёт указанный формат. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Sets the format of a particular image
Description: Sets the format of a particular image in a sequence.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page fc50f5a3588b2315c7a5d6a4cec72e90fb8f870277caec311e6688e634ff4ac8; XML 216082fec9a61e3457263a2c01d5aec31e49fbd41594ffea20eee143d3b3bd53.
Imagick::setImageProfileProfile появляется под заданным именем.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::setImageProfile(string $name, string $profile): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно прикрепить уже проверенный бинарный профиль к кадру
- Метод получает явно подготовленное состояние и параметры
- После вызова profile появляется под заданным именем
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Прикрепить уже проверенный бинарный профиль к кадру.
Сигнатура. Imagick::setImageProfile(string $name, string $profile): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка. |
string $profile | Бинарные данные доверенного профиля; null в profileImage удаляет профиль. |
Возврат и видимый итог. Profile появляется под заданным именем.
Соседний выбор. profileImage() для операции добавления/удаления и color workflow.
Точные соседние карточки. Imagick::getImageProfile · Imagick::getImageProfiles.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$profile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($profile === false || strlen($profile) > 1_000_000) {
throw new \RuntimeException('Не прочитан ограниченный XMP profile');
}
$result = $image->setImageProfile('xmp', $profile);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setImageProfile',
'returned' => aenObserve('Imagick::setImageProfile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: profile появляется под заданным именем. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$profile = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($profile === false || strlen($profile) > 1_000_000) {
throw new \RuntimeException('Не прочитан ограниченный XMP profile');
}
$result = $image->setImageProfile('xmp', $profile);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$profileNames = $image->getImageProfiles('*', false);
$xmpAttached = in_array('xmp', $profileNames, true);
if (!$xmpAttached) { throw new \RuntimeException('XMP profile не прикреплён'); }
$observation = [
'method' => 'Imagick::setImageProfile',
'returned' => aenObserve('Imagick::setImageProfile', $result),
'effect' => aenObserve('Imagick::setImageProfile:effect', $xmpAttached),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: profile появляется под заданным именем. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Adds a named profile to the Imagick object
Description: Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 710013363f56923549a765ee2247543304986326ba8fd86275900602248b35fe; XML f9e8c14a76888b8c311c3336302e591f1c9f486041bab35bc5a77019a427ec7e.
Imagick::setImagePropertyProperty доступно через getimageproperty() и может попасть в output.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::setImageProperty(string $name, string $value): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно сохранить одно именованное свойство изображения
- Метод получает явно подготовленное состояние и параметры
- После вызова property доступно через getImageProperty() и может попасть в output
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Сохранить одно именованное свойство изображения.
Сигнатура. Imagick::setImageProperty(string $name, string $value): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $name | Точное имя property/profile, выбранное из разрешённого списка. |
string $value | Строковое значение текущей option/property/artifact/registry. |
Возврат и видимый итог. Property доступно через getimageproperty() и может попасть в output.
Соседний выбор. commentImage()/labelImage() для стандартных смыслов.
Точные соседние карточки. Imagick::getImageProperty.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageProperty('aen:asset-id', 'asset-42');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::setImageProperty',
'returned' => aenObserve('Imagick::setImageProperty', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: property доступно через getImageProperty() и может попасть в output. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->setImageProperty('aen:source', 'catalog-import');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$storedSource = $image->getImageProperty('aen:source');
$observation = [
'method' => 'Imagick::setImageProperty',
'returned' => aenObserve('Imagick::setImageProperty', $result),
'effect' => aenObserve('Imagick::setImageProperty:effect', $storedSource),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: property доступно через getImageProperty() и может попасть в output. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Sets an image property
Description: Sets a named property to the image. Available since Imagick 6.3.2.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::getImageProperty
Source hashes: page 81ab30a5e26f579a4cadc0faeb58190e1a18ff1faac2a91c796add16db0a0b81; XML 69768257148b5fa380023b31ce3c935634c0199a09808ae2fff3a605f9ecafe0.
Imagick::stripImageВыходной кадр теряет exif/iptc/xmp/icc и другие профили.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::stripImage(): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно удалить comments и profiles перед публикацией web-копии
- Метод получает явно подготовленное состояние и параметры
- После вызова выходной кадр теряет EXIF/IPTC/XMP/ICC и другие профили
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Удалить comments и profiles перед публикацией web-копии.
Сигнатура. Imagick::stripImage(): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Выходной кадр теряет exif/iptc/xmp/icc и другие профили.
Соседний выбор. точечно удалить приватные свойства, сохранив нужный ICC.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$privateXmp = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($privateXmp === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $privateXmp);
$result = $image->stripImage();
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::stripImage',
'returned' => aenObserve('Imagick::stripImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: выходной кадр теряет EXIF/IPTC/XMP/ICC и другие профили. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$privateXmp = file_get_contents(__DIR__ . '/fixtures/metadata.xmp');
if ($privateXmp === false) { throw new \RuntimeException('Не прочитан XMP fixture'); }
$image->setImageProfile('xmp', $privateXmp);
$result = $image->stripImage();
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$profilesAfterStrip = $image->getImageProfiles('*', false);
if ($profilesAfterStrip !== []) { throw new \RuntimeException('Не все профили удалены'); }
$publicWritten = $image->writeImage(__DIR__ . '/out/public-copy.ppm');
if ($publicWritten !== true || !is_file(__DIR__ . '/out/public-copy.ppm')) { throw new \RuntimeException('Public copy не записана'); }
$observation = [
'method' => 'Imagick::stripImage',
'returned' => aenObserve('Imagick::stripImage', $result),
'effect' => aenObserve('Imagick::stripImage:effect', $publicWritten),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: выходной кадр теряет EXIF/IPTC/XMP/ICC и другие профили. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Strips an image of all profiles and comments
Description: Strips an image of all profiles and comments.
Return: Returns true on success.
Errors: Throws ImagickException on error.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 1c23cdab3f60f00b17234d1378d5a1b13f125423832d9316aad763167fc29c8a; XML 13fa14e5729a54172feb86d2dac74ddc54905898b371b6f8e5941cc5d11bebd0.
Imagick::__toStringСтрока содержит encoded bytes текущего кадра.
PECL imagick 2, PECL imagick 3 · imagick
Imagick::__toString(): stringПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно получить бинарное представление текущего image через строковое преобразование
- Метод получает явно подготовленное состояние и параметры
- После вызова строка содержит encoded bytes текущего кадра
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Получить бинарное представление текущего image через строковое преобразование.
Сигнатура. Imagick::__toString(): string
Модификаторы вызова. public. Это метод конкретного объекта $image.
Параметров нет: вызов читает или меняет состояние текущего объекта.
Возврат и видимый итог. Строка содержит encoded bytes текущего кадра.
Соседний выбор. getImageBlob() для более явного намерения.
Точные соседние карточки. Imagick::getImageBlob · Imagick::getImagesBlob.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->__toString();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
$observation = [
'method' => 'Imagick::__toString',
'returned' => aenObserve('Imagick::__toString', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: строка содержит encoded bytes текущего кадра. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->__toString();
if ($result === '') { throw new \RuntimeException('Получена пустая строка'); }
if (!str_starts_with($result, 'P6')) { throw new \RuntimeException('String cast не содержит PPM'); }
$written = file_put_contents(__DIR__ . '/out/string-cast-image.ppm', $result, LOCK_EX);
if ($written !== strlen($result)) { throw new \RuntimeException('Binary string записана не полностью'); }
$observation = [
'method' => 'Imagick::__toString',
'returned' => aenObserve('Imagick::__toString', $result),
'effect' => aenObserve('Imagick::__toString:effect', $written),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: строка содержит encoded bytes текущего кадра. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Returns the image as a string
Description: Returns the current image as string. This will only return a single image; it should not be used for Imagick objects that contain multiple images e.g. an animated GIF or PDF with multiple pages.
Return: Returns the string content on success or an empty string on failure.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::getImageBlob, Imagick::getImagesBlob
Source hashes: page 27ffcb890b8382471749ac5ee39b9b9bd0096ee1755c0256b65591a1a2110cd7; XML a7948c7a4fa1590d92a72922baef8584931bd97b6fd7b124f8726fcbb5fd9560.
Imagick::writeImageНа диске появляется файл выбранного coder/filename.
PECL imagick 2 >= 2.3.0, PECL imagick 3 · imagick
Imagick::writeImage(string $filename = NULL): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно записать текущий кадр в явный локальный файл
- Метод получает явно подготовленное состояние и параметры
- После вызова на диске появляется файл выбранного coder/filename
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Записать текущий кадр в явный локальный файл.
Сигнатура. Imagick::writeImage(string $filename = NULL): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $filename = NULL | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога.Точная формулировка PHP ManualFilename where to write the image. The extension of the filename defines the type of the file. Format can be forced regardless of file extension using format: prefix, for example "jpg:test.png". |
Возврат и видимый итог. На диске появляется файл выбранного coder/filename.
Соседний выбор. writeImageFile() для открытого stream.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageFormat('png');
$result = $image->writeImage(__DIR__ . '/out/product-preview.png');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::writeImage',
'returned' => aenObserve('Imagick::writeImage', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: на диске появляется файл выбранного coder/filename. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->setImageFormat('webp');
$result = $image->writeImage(__DIR__ . '/out/page-1.webp');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$output = __DIR__ . '/out/page-1.webp';
if (!is_file($output) || filesize($output) === 0) { throw new \RuntimeException('Output файл не появился'); }
$observation = [
'method' => 'Imagick::writeImage',
'returned' => aenObserve('Imagick::writeImage', $result),
'effect' => aenObserve('Imagick::writeImage:effect', $output),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: на диске появляется файл выбранного coder/filename. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2 >= 2.3.0, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Writes an image to the specified filename
Description: Writes an image to the specified filename. If the filename parameter is NULL, the image is written to the filename set by Imagick::readImage() or Imagick::setImageFilename().
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 63bc43558ee202ea0210e610da347a9f87f4cfbb6db43979e00428ad37f2b34c; XML a5c450d8f60837dfeaf73219bbdf37ff17ae6c1960c79b8702302417a6c0b40f.
Imagick::writeImageFileEncoded bytes уходят в stream без скрытого output path.
PECL imagick 2 >= 2.3.0, PECL imagick 3 · imagick
Imagick::writeImageFile(resource $filehandle, string $format = ?): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно записать один кадр в открытый PHP file handle
- Метод получает явно подготовленное состояние и параметры
- После вызова encoded bytes уходят в stream без скрытого output path
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Записать один кадр в открытый php file handle.
Сигнатура. Imagick::writeImageFile(resource $filehandle, string $format = ?): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
resource $filehandle | Проверенный открытый binary stream в нужном режиме и позиции.Точная формулировка PHP ManualFilehandle where to write the image. |
string $format = значение по умолчанию | Имя coder вроде 'png' или 'jpeg', предварительно проверенное queryFormats().Точная формулировка PHP ManualThe image format. The list of valid format specifiers depends on the compiled feature set of ImageMagick, and can be queried at runtime via Imagick::queryFormats . |
Возврат и видимый итог. Encoded bytes уходят в stream без скрытого output path.
Соседний выбор. getImageBlob()+fwrite() для полного контроля ценой памяти.
Точные соседние карточки. Imagick::queryFormats.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$handle = fopen(__DIR__ . '/out/preview.png', 'wb');
if ($handle === false) { throw new \RuntimeException('Не открыт output stream'); }
$result = $image->writeImageFile($handle, 'png');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::writeImageFile',
'returned' => aenObserve('Imagick::writeImageFile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: encoded bytes уходят в stream без скрытого output path. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$handle = fopen(__DIR__ . '/out/preview.webp', 'wb');
if ($handle === false) { throw new \RuntimeException('Не открыт output stream'); }
$result = $image->writeImageFile($handle, 'webp');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
fflush($handle);
$streamPosition = ftell($handle);
if ($streamPosition === false || $streamPosition === 0) { throw new \RuntimeException('Stream остался пустым'); }
$observation = [
'method' => 'Imagick::writeImageFile',
'returned' => aenObserve('Imagick::writeImageFile', $result),
'effect' => aenObserve('Imagick::writeImageFile:effect', $streamPosition),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: encoded bytes уходят в stream без скрытого output path. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2 >= 2.3.0, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Writes an image to a filehandle
Description: Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. Available since Imagick 6.3.6.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::queryFormats
Source hashes: page 739374bb685adb407ef13d3d77d788ab2a435ce35f2629ac5cd8167ef7936729; XML e578833107537b46dd2aa6924a063c8271f60bb2676e6eed0e2f79541f18cb44.
Imagick::writeImagesAdjoin=true создаёт единый поддерживаемый контейнер; false — отдельные outputs.
PECL imagick 2 >= 2.3.0, PECL imagick 3 · imagick
Imagick::writeImages(string $filename, bool $adjoin): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно записать всю последовательность как один multiframe файл либо раздельные файлы
- Метод получает явно подготовленное состояние и параметры
- После вызова adjoin=true создаёт единый поддерживаемый контейнер; false — отдельные outputs
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Записать всю последовательность как один multiframe файл либо раздельные файлы.
Сигнатура. Imagick::writeImages(string $filename, bool $adjoin): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
string $filename | Контролируемый локальный путь; canonical path должен оставаться внутри разрешённого каталога. |
bool $adjoin | true пытается записать единый multiframe container, false — раздельные outputs. |
Возврат и видимый итог. Adjoin=true создаёт единый поддерживаемый контейнер; false — отдельные outputs.
Соседний выбор. writeImage() в явном цикле для пофайловых имён.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$result = $image->writeImages(__DIR__ . '/out/animation.gif', true);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::writeImages',
'returned' => aenObserve('Imagick::writeImages', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: adjoin=true создаёт единый поддерживаемый контейнер; false — отдельные outputs. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->readImage(__DIR__ . '/fixtures/back.ppm');
$result = $image->writeImages(__DIR__ . '/out/page-%02d.png', false);
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$writtenPages = glob(__DIR__ . '/out/page-*.png') ?: [];
if (count($writtenPages) !== $image->getNumberImages()) { throw new \RuntimeException('Записаны не все кадры'); }
$observation = [
'method' => 'Imagick::writeImages',
'returned' => aenObserve('Imagick::writeImages', $result),
'effect' => aenObserve('Imagick::writeImages:effect', $writtenPages),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: adjoin=true создаёт единый поддерживаемый контейнер; false — отдельные outputs. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2 >= 2.3.0, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Writes an image or image sequence
Description: Writes an image or image sequence.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: на странице не указано
Source hashes: page 1c86c9ffa7905138f0fd27ce565591b4e70d51fa0f58c1aa37cd84c3dbe64bd3; XML 454767515af20b8e014e9ee977a27264a06622671617b0256c51cbba5dae2bbd.
Imagick::writeImagesFileStream получает multiframe container.
PECL imagick 2 >= 2.3.0, PECL imagick 3 · imagick
Imagick::writeImagesFile(resource $filehandle, string $format = ?): boolПеред примером. Если термин незнаком, откройте: объект и метод · static и область состояния · массив · поток и ресурс · исключение · строка и бинарные байты · callback. Ссылки ведут к самостоятельным объяснениям и не заменяют разбор ниже.
- Нужно записать все кадры в открытый stream
- Метод получает явно подготовленное состояние и параметры
- После вызова stream получает multiframe container
- Код проверяет отказ до следующего шага pipeline
Что делает именно этот метод. Записать все кадры в открытый stream.
Сигнатура. Imagick::writeImagesFile(resource $filehandle, string $format = ?): bool
Модификаторы вызова. public. Это метод конкретного объекта $image.
| Параметр | Как читать |
|---|---|
resource $filehandle | Проверенный открытый binary stream в нужном режиме и позиции.Точная формулировка PHP ManualFilehandle where to write the images. |
string $format = значение по умолчанию | Имя coder вроде 'png' или 'jpeg', предварительно проверенное queryFormats().Точная формулировка PHP ManualThe image format. The list of valid format specifiers depends on the compiled feature set of ImageMagick, and can be queried at runtime via Imagick::queryFormats . |
Возврат и видимый итог. Stream получает multiframe container.
Соседний выбор. writeImages() во временный файл для atomic publication.
Точные соседние карточки. Imagick::queryFormats.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$handle = fopen(__DIR__ . '/out/animation.gif', 'wb');
if ($handle === false) { throw new \RuntimeException('Не открыт output stream'); }
$result = $image->writeImagesFile($handle, 'gif');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
$observation = [
'method' => 'Imagick::writeImagesFile',
'returned' => aenObserve('Imagick::writeImagesFile', $result),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Предусловия: PHP с PECL imagick, совместимой ImageMagick и локальным тестовым файлом. После запуска в таком окружении следует проверить: stream получает multiframe container. Здесь выполнена только проверка синтаксиса PHP, потому что расширение Imagick не загружено.
<?php
declare(strict_types=1);
function aenObserve(string $method, mixed $value): mixed
{
if (is_string($value)) {
$binaryMethod = str_contains($method, 'Blob') || (str_contains($method, 'Profile') && !str_contains($method, ':names')) || str_contains($method, '__toString');
$isUtf8 = preg_match('//u', $value) === 1;
$hasControlBytes = preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $value) === 1;
if ($binaryMethod || !$isUtf8 || $hasControlBytes) {
return ['bytes' => strlen($value), 'sha256' => hash('sha256', $value)];
}
if (strlen($value) <= 512) { return $value; }
return ['preview' => substr($value, 0, 240), 'bytes' => strlen($value), 'truncated' => true];
}
if (is_array($value)) {
$visible = [];
foreach (array_slice($value, 0, 12, true) as $key => $item) {
$visible[$key] = aenObserve($method . ':item', $item);
}
return ['items' => count($value), 'values' => $visible, 'truncated' => count($value) > 12];
}
if (is_object($value)) { return ['class' => get_class($value)]; }
return $value;
}
$image = null;
$result = null;
$handle = null;
$draw = null;
$probe = null;
$oldResourceLimit = null;
$resourceType = null;
$registryKey = null;
$registryOldValue = null;
$registryHadValue = false;
try {
$outputDirectory = __DIR__ . '/out';
if (!is_dir($outputDirectory) && !mkdir($outputDirectory, 0770, true) && !is_dir($outputDirectory)) {
throw new \RuntimeException('Не удалось создать локальный output-каталог');
}
$image = new \Imagick();
$image->readImage(__DIR__ . '/fixtures/product.ppm');
$image->readImage(__DIR__ . '/fixtures/back.ppm');
$handle = fopen(__DIR__ . '/out/sequence.tiff', 'wb');
if ($handle === false) { throw new \RuntimeException('Не открыт output stream'); }
$result = $image->writeImagesFile($handle, 'tiff');
if ($result !== true) { throw new \RuntimeException('Imagick не подтвердил операцию'); }
fflush($handle);
$sequenceBytes = ftell($handle);
if ($sequenceBytes === false || $sequenceBytes === 0) { throw new \RuntimeException('Sequence stream пуст'); }
$observation = [
'method' => 'Imagick::writeImagesFile',
'returned' => aenObserve('Imagick::writeImagesFile', $result),
'effect' => aenObserve('Imagick::writeImagesFile:effect', $sequenceBytes),
];
if ($image instanceof \Imagick) { $observation['frames_after'] = $image->getNumberImages(); }
echo json_encode($observation, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (\ImagickException $exception) {
throw new \RuntimeException('Image pipeline отклонён', 0, $exception);
} finally {
if (is_resource($handle)) { fclose($handle); }
if ($draw instanceof \ImagickDraw) { $draw->clear(); }
if ($probe instanceof \Imagick) { $probe->clear(); }
if ($result instanceof \Imagick && $result !== $image) { $result->clear(); }
if ($image instanceof \Imagick) { $image->clear(); }
}
Сценарий использует метод внутри ограниченного обработчика изображений и выполняет отдельный следующий шаг. При проверке в окружении с Imagick нужно подтвердить: stream получает multiframe container. Ошибка не маскируется: ImagickException превращается в отказ задания с исходной причиной. Выполнение здесь не заявлено.
| Граница | Официальные данные |
|---|---|
| Доступно с | PECL imagick 2 >= 2.3.0, PECL imagick 3 |
| Deprecated | Нет отметки |
| Удалено | Нет отметки |
Официальный договор без сокращений
Purpose: Writes frames to a filehandle
Description: Writes all image frames into an open filehandle. This method can be used to write animated gifs or other multiframe images into open filehandle. Available since Imagick 6.3.6.
Return: Returns true on success.
Errors: Not stated on the source page.
Changelog: No page-specific changelog entry.
See also: Imagick::queryFormats
Source hashes: page d29989501fc5a42f92ff75e7b63dddb8ab118ff7d2d631958485a3a77e540e35; XML 214c5db0b3eb366f5fad01324b34bc3e4b3e5ace067e9c4c6caca602c75cd332.
Код и руководство с собой
Скачайте самостоятельные примеры с исходными данными, инструкциями и ожидаемыми результатами. Примеры HTTP и фрагменты для проекта помечены отдельно: им нужно указанное окружение.
Код не исполняется на сайте. Скачайте нужный пример и запускайте его в своём локальном окружении.
Материалы сверены 2026-10-12. Примеры и объяснения написаны для этого руководства; источники и обсуждения доступны в каждой главе.


