converter-studio / converter-studio-php
Official PHP client for the Converter Studio API: convert HEIC, RAW photos, video, audio, documents and e-books from PHP.
Package info
github.com/tariksucu/converter-studio-php
pkg:composer/converter-studio/converter-studio-php
Requires
- php: ^8.2
- ext-curl: *
- ext-json: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpstan/phpstan-phpunit: ^2.1
- phpstan/phpstan-strict-rules: ^2.1
- phpunit/phpunit: ^11.5 || ^12.5 || ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
The official PHP client for the Converter Studio API. Convert iPhone photos (HEIC), camera RAW photos, videos, audio, documents, spreadsheets, presentations, e-books, subtitles, fonts, data files and archives (67 formats) from your PHP code. The conversion runs on Converter Studio's servers, so there is nothing else to install on yours: no ImageMagick, no FFmpeg, no LibreOffice.
use ConverterStudio\Client; $client = new Client(); // the API key comes from CONVERTER_STUDIO_API_KEY $conversion = $client->convert('IMG_1234.HEIC', 'jpg'); $client->download($conversion, 'photos/'); // photos/IMG_1234.jpg
- No dependencies: PHP 8.2 or later with the curl extension. Works in any framework (Laravel, Symfony, WordPress, plain PHP) and from the command line.
- Local files, streams, bytes in memory, or links (direct links and Google Drive, Dropbox or OneDrive share links), with any of the API's conversion settings.
- Large files are uploaded in parts on their own; uploads and downloads are streamed, so a file is never held in memory.
- Waiting with long polling and a back-off, retries with an
Idempotency-Keyso a retry never starts or charges a second conversion, and exceptions that carry the API's code and message. - Typed read-only results (
Conversion,Format,Account), checked with PHPStan at its highest level.
Installation
$ composer require converter-studio/converter-studio-php
Then create an API key on your account page (keys
start with cvs_live_; keep them secret) and put it in the environment:
$ export CONVERTER_STUDIO_API_KEY=cvs_live_...
Every conversion uses your account's credits, the same as on the website: free accounts get credits every day, Pro and Premium their monthly credits. Most files cost 1 credit; audio and video are priced by their length (video also by its frame size and the format made) once Converter Studio has looked at them. See pricing.
Usage
Convert a file
use ConverterStudio\Client; $client = new Client(); // or new Client('cvs_live_...') $conversion = $client->convert('talk.mov', 'mp4', options: ['height' => '720']); echo $conversion->status, ' ', $conversion->credits, ' ', $conversion->outputName; // done 1 talk.mp4 $path = $client->download($conversion, 'out/'); // a folder (ending in / or existing), or a file path
convert() uploads the file, starts the conversion and waits until it is done (10 minutes at
most by default: timeout:). The source can be:
- a path:
'photos/IMG_1234.HEIC'; - a link (a string starting with
http://orhttps://): Converter Studio fetches the file itself, so it never passes through your server; - an open stream:
$client->convert(fopen('song.flac', 'rb'), 'mp3'), read from where it stands (passfileName:when the stream has no name, such asphp://input); - bytes in memory, with a name:
$client->convert(Source::fromContents($bytes, 'report.docx'), 'pdf').
ConverterStudio\Source also has fromPath() and fromUrl(), to say which a string is (a local
file whose name starts with http).
download() never replaces an existing file in a folder unless overwrite: true: the result
gets -1, -2... before its extension. The file appears only once it is complete. You can also
stream the result to any open stream, such as the browser:
header('Content-Type: image/jpeg'); $client->downloadTo($conversion, fopen('php://output', 'wb'));
or get it in memory ($client->downloadContents($conversion)). Results are kept for 6 hours, and
anyone with $conversion->downloadUrl can download the result until $conversion->expiresAt.
Settings
options takes the API's conversion settings, the same as on the website. A few of them:
| Setting | For |
|---|---|
quality: 'high', 'balanced', 'small' |
video, JPG, WebP, AVIF |
height: '1080', '720', '480', '360' |
video (never upscaled) |
maxSize: MB |
MP4 that must fit a size |
maxKb: KB |
JPG, WebP, AVIF that must fit a size |
longSide, resizeWidth, resizeHeight, fit |
resizing images |
keepMetadata, keepLocation: true |
keep a photo's camera details and GPS (off) |
bitrate: '64'... '320', channels, trimStart, trimEnd |
audio |
pageRange: '1-3, 5', pdfA: true |
documents to PDF |
ocr: true, ocrLanguage |
scanned PDFs to Word or text |
compression: 'light', 'balanced', 'strong' |
PDF to a smaller PDF |
password |
a locked ZIP, 7Z or RAR (used once, never stored) |
The full list, and which settings apply to which conversion, is on the
API page. Settings that do not apply to a conversion are
ignored; a name the API does not know is refused (BadRequestException).
Formats and account
foreach ($client->formats() as $format) { // no key needed echo $format->id, ' -> ', implode(', ', $format->targets), "\n"; } $heic = $client->formats('heic')[0]; // what HEIC converts to $account = $client->account(); echo $account->plan, ' ', $account->credits, ' ', $account->renewsAt?->format('Y-m-d');
Price limits
A conversion goes ahead on its own when it costs at most maxCredits (20 by default). A dearer
one waits for your go-ahead and costs nothing until then:
use ConverterStudio\Exception\ConfirmationRequiredException; try { $conversion = $client->convert('lecture.mkv', 'mp4', maxCredits: 5); } catch (ConfirmationRequiredException $quoted) { echo "It costs {$quoted->credits} credits\n"; $conversion = $client->wait($client->confirm($quoted->conversion)); }
maxCredits: 0 only gets the price.
Step by step
convert() is built from these, which you can call yourself:
$upload = $client->upload('scan.pdf'); // large files go in parts $created = $client->createConversion('docx', uploadId: $upload->id, options: ['ocr' => true]); $created = $client->createConversion('jpg', url: 'https://example.com/photo.heic'); $current = $client->getConversion($created->id); // status now $current = $client->getConversion($created->id, wait: 30); // the API holds the answer up to 30 s $done = $client->wait($created, timeout: 900);
wait() returns a finished conversion or throws (see Errors). It lets the API hold
each status request until something changes, and pauses between answers that come back early (1
second, doubling up to 10). convert(..., wait: false) returns as soon as the conversion has
started.
Callbacks and retries
$created = $client->createConversion( 'mp4', url: 'https://example.com/raw/clip.mov', callbackUrl: 'https://example.com/hooks/converter-studio?token=SECRET', idempotencyKey: 'clip-42', );
callbackUrl: anhttps://address on the public internet that Converter Studio POSTs to when the conversion waits for a go-ahead (conversion.quoted) and when it ends (conversion.done,conversion.failedorconversion.canceled). The body is{"event", "id", "createdAt", "conversion"}, withWebhook-IdandWebhook-Timestampheaders. Callbacks are not signed: keep the address secret, and check the conversion with$client->getConversion(...)before acting on one.idempotencyKey: sending the same request again with the same key (within 24 hours) returns the first conversion ($conversion->replayedistrue) instead of starting and charging a second one; the same key with a different request throwsConflictException. The client makes up a key for eachcreateConversion()call and reuses it for its own retries, so pass your own when your code itself may repeat a request (a queue worker retrying a job). With a local file, upload it once and repeatcreateConversion(uploadId: ...)with the same key.
Errors
Every exception derives from ConverterStudio\Exception\ConverterStudioException, and
getMessage() is a sentence meant for people (for API errors, the API's own message). Wrong
arguments throw PHP's InvalidArgumentException.
Exception (in ConverterStudio\Exception) |
When |
|---|---|
ApiException |
the API answered with an error: ->statusCode, ->errorCode (notEnoughCredits...), ->params |
AuthenticationException (401) |
the API key does not work |
InsufficientCreditsException (402) |
not enough credits (params: needed, balance) |
FileTooLargeException (413), UnprocessableException (422) |
the file is over the plan's limit; the file cannot be converted that way (unsupportedConversion) |
BadRequestException, NotFoundException, ConflictException, GoneException, PermissionDeniedException |
400, 404, 409, 410, 403 |
RateLimitException (429), ServerException (5xx) |
retried on their own first (maxRetries, 2 by default); ->retryAfter in seconds |
ConversionFailedException |
the conversion failed, expired or was canceled: ->errorCode, ->conversion; failures are not charged |
ConfirmationRequiredException |
the price is over maxCredits: ->credits, ->conversion |
ConversionTimeoutException |
not done within timeout; it may still finish (->conversion->id) |
MissingApiKeyException, ApiConnectionException, ApiTimeoutException |
no key; the API could not be reached |
LocalFileException |
a local file could not be read or written (or is already there) |
use ConverterStudio\Exception\ApiException; use ConverterStudio\Exception\ConversionFailedException; try { $client->convert('broken.heic', 'jpg'); } catch (ConversionFailedException $failed) { echo $failed->errorCode, ': ', $failed->getMessage(); } catch (ApiException $error) { echo $error->statusCode, ' ', $error->errorCode, ': ', $error->getMessage(); }
Configuration
use ConverterStudio\Client; use ConverterStudio\Http\CurlTransport; $client = new Client( apiKey: 'cvs_live_...', // default: CONVERTER_STUDIO_API_KEY baseUrl: 'https://converter.studio/api', // default: CONVERTER_STUDIO_BASE_URL or this timeout: 60.0, // seconds to connect, and seconds a request may go without progress maxRetries: 2, // network errors, 408, 429, 5xx transport: new CurlTransport([CURLOPT_PROXY => 'http://proxy:3128']), // curl options of your own );
The API key is only sent to baseUrl; upload and download links carry their own tokens. It is
kept out of var_dump(), print_r() and stack traces, and a client cannot be serialized.
Requests go through PHP's curl extension; a class of your own that implements
ConverterStudio\Http\Transport can send them instead.
Limits
- The largest file depends on the plan (
$client->account()->maxFileBytes). One request carries up to 95 MB; the client sends larger files in parts on its own. - Audio and video length also depends on the plan (
maxMediaSeconds). - Results are kept for 6 hours, then deleted. A status request can wait up to 60 seconds.
- One file in, one file out: no merging or splitting of PDFs.
Privacy
Your files are sent to Converter Studio (converter.studio) to be converted. Uploaded files are
deleted as soon as they are converted, and results 6 hours later. Each request also says which
client sent it (X-Converter-Studio-Client: php/<version>), for usage statistics only. See the
privacy policy and the terms.
Links
- Converter Studio: https://converter.studio
- API documentation: https://converter.studio/developers
- Pricing: https://converter.studio/pricing
- Source code and issues: https://github.com/tariksucu/converter-studio-php
- Changelog: https://github.com/tariksucu/converter-studio-php/blob/main/CHANGELOG.md
- Support: support@converter.studio
MIT licensed. © Converter Studio.