Перейти к основному содержимому

Преобразовать формат изображения API

Что делает эта конечная точка: Он PDF4me Преобразовать формат изображения REST API преобразует изображения между JPG, PNGWebP, BMP, GIF и TIFF форматы в одном POST Пришлите исходное изображение в формате... Base64— Закодированная строка, укажите текущий формат и целевой формат, и получите обратно преобразованное изображение, также в виде Base64Используйте его для стандартизации форматов изображений в рамках всего конвейера обработки, преобразования устаревших форматов BMP или TIFF файлы для доставки через Интернет или для подготовки изображений перед их обработкой с помощью конечной точки сжатия изображений.

Похожие записи в блоге
Пока нет публикации в блоге, посвященной этой функции — она скоро появится.
А пока что, загляните в блог PDF4me, где вы найдете обучающие материалы и рабочие процессы для всех платформ.
Посетите блог →

Аутентификация вашего API Запрос​

Каждый PDF4me REST API В звонке необходимо указать ваш API ключ в Authorization заголовок. Получите свой ключ на панели разработчика и не используйте его в клиентском коде.

Важные факты, которые нельзя пропустить​

All four parameters are required: including both format fields

docName, docContent, CurrentImageFormat, and NewImageFormat must all be present. A missing format parameter causes the API to return a 400 error. Always provide both format fields explicitly: do not assume the API will infer the source format from the file extension in docName.

CurrentImageFormat must match the actual binary format of docContent

The API uses CurrentImageFormat to select the correct decoding codec. If you send a PNG file but set CurrentImageFormat to JPG, decoding fails with a format error. Read the real format from your source file MIME type or binary header: never derive it solely from the filename extension, which can be wrong.

PNG transparency is lost when converting to JPG: use PNG, GIF, or BMP to keep alpha

JPG does not support an alpha channel. Transparent areas in a PNG or GIF source are filled with white (or a default background) during JPG conversion. If your image has a transparent background: logos, cut-out product photos, icons, convert to PNG, GIF, or BMP instead of JPG to preserve the transparency.

REST API Конечная точка​

МетодКонечная точка
POST/api/v2/ConvertImageFormat

Базовый URL: https://api.pdf4me.com

Параметры​

⚠️ Необходимы все четыре параметра. Он API Возвращает ошибку, если какое-либо поле отсутствует.

ПараметрНеобходимыйТипЧто это делаетПример
docNameRequiredStringFilename of the source image including the file extension. Used for output file naming. Should reflect the actual format of the source file.company-logo.png
docContentRequiredBase64The complete source image file encoded as a Base64 string. Maximum file size: 50 MB. Do not include a data URL prefix: pass the raw Base64 string only.iVBORw0KGgoAAAANSUhEUg...
CurrentImageFormatRequiredEnumThe actual format of the source image in docContent. Must match exactly. Accepted values: BMP · GIF · JPG · PNG · TIFFPNG
NewImageFormatRequiredEnumThe target format for the converted output image. Accepted values: BMP · GIF · JPG · PNG · TIFFJPG

Поля вывода​

ПараметрНеобходимыйЧто это делаетПример
jobIdExtOptionalYour own reference for this call. It is stored with the API call log so you can correlate calls with your jobs. Type: string.
integrationsOptionalIntegration identifiers, forwarded unchanged with the job's notification settings. Type: array.
isAsyncOptionalSet to `true` to process the action asynchronously and get a job to poll at `/api/v2/GetActionStatus`. Only honoured by actions that support asynchronous processing. Type: boolean.
docNameOptionalSource file name including its extension. Several actions dispatch on the extension, so it should always be set; when omitted a per-action default is used. Type: string.Filename of the converted output image.
docContentRequiredThe source file. Accepts the base64-encoded file content, a `pdf4meblobid://<id>` reference to a previously uploaded blob, or an `https` URL to the source document. Required: an empty value fails with `File is empty`. Type: string.The converted image encoded as Base64. Decode to binary and save with the correct new file extension.
docContentBytesOptionalAlternative raw byte payload for the source file. Type: string.
callBackUrlOptionalOptional URL notified when an asynchronous job completes. Type: string.
currentImageFormatOptionalMatched case-insensitively; an unrecognised value falls back to the first entry. Type: string.
newImageFormatOptionalMatched case-insensitively; an unrecognised value falls back to the first entry. Type: string.

Пример запроса​

Заголовки​

Content-Type: application/json
Authorization: YOUR_API_KEY

JSON-полезная нагрузка​

{
"docName": "company-logo.png",
"docContent": "iVBORw0KGgoAAAANSUhEUg...",
"CurrentImageFormat": "PNG",
"NewImageFormat": "JPG"
}

Ответ​

{
"File Content": "BASE64_CONVERTED_IMAGE_DATA",
"File Name": "company-logo.jpg"
}

Примеры кода​

Типичные сценарии использования​

Standardise Legacy Assets to PNG for Web Delivery

Marketing teams often accumulate mixed BMP, TIFF, and GIF files from various sources. Convert them all to PNG in a batch processing loop: PNG gives lossless quality and wide browser support, making it the safest default web format for logos and graphics.

Convert Product Photography from TIFF to JPG

Studio photographs are typically delivered as TIFF (50-200 MB each). Convert to JPG before uploading to your e-commerce platform or CDN to reduce storage costs by 80-90%. Pair with the Compress Image endpoint for a complete optimisation pipeline.

Prepare Images for WebP Delivery

WebP images are 25-35% smaller than equivalent JPGs and supported by all modern browsers. Convert JPG or PNG assets to WebP to improve Core Web Vitals scores. Serve WebP with a JPG fallback using HTML picture elements.

Часто задаваемые вопросы​

▶ What image formats does the Convert Image Format API support?

The API supports BMP, GIF, JPG, PNG, and TIFF as both input (CurrentImageFormat) and output (NewImageFormat). These five formats cover the most common image types used in enterprise and web workflows.

▶ Does CurrentImageFormat need to match the actual binary format of docContent?

Yes: always. The API uses CurrentImageFormat to select the correct decoding codec. A mismatch between the actual binary format and CurrentImageFormat causes a decoding failure. Read the real format from your file's MIME type or binary signature, not just the filename extension.

▶ How does PNG-to-JPG conversion handle transparency?

JPG does not support an alpha channel. Transparent areas in a PNG source are replaced with a solid background colour (typically white) during conversion. If preserving transparency matters: logos, product cut-outs, icons, convert to PNG, GIF, or BMP instead of JPG.

▶ Can I convert and compress an image in the same API call?

No: Convert Image Format only changes the format. To also compress, call Convert Image Format first to get the target format, then pass the result's File Content to the Compress Image endpoint with your chosen compression level. Chain both calls in your application.

▶ What is the maximum file size accepted by this endpoint?

Up to 50 MB. For best performance keep images under 10 MB. Note that format conversion can change file size: converting a PNG to JPG typically reduces size, while converting JPG to TIFF may increase it significantly.

Связанный APIs​

Сжать изображение
Уменьшите размер файла при максимальном, среднем или низком качестве, добавьте эту операцию после преобразования формата изображения для получения полного конвейера преобразования и сжатия.
Получить метаданные изображения
Перед преобразованием извлеките текущий формат, размеры и разрешение (DPI), используйте это для программного подтверждения параметра CurrentImageFormat.
Изменить размер изображения
Масштабируйте размеры изображения до целевой ширины и высоты, а в сочетании с функцией «Преобразовать формат изображения» выполните полную нормализацию формата и размера.

Получить помощь​