Official PHP SDK for the ToSVG API — Convert images to SVG, remove backgrounds, and resize images.
- PHP 8.1 or higher
- Composer
- A ToSVG API key (Get one here)
composer require tosvg/tosvg-phpuse ToSVG\ToSVGClient;
$client = new ToSVGClient('tosvg_live_your_api_key');
// Convert an image to SVG
$result = $client->convert->imageToSvg('/path/to/image.png');
echo $result->svg;Your API key has the format tosvg_{live|test}_<32-char-random-string>:
tosvg_live_— Production keytosvg_test_— Sandbox key
$client = new ToSVGClient('tosvg_live_your_api_key');use ToSVG\ToSVGClient;
use Monolog\Logger;
$client = new ToSVGClient(
apiKey: 'tosvg_live_your_api_key',
config: [
'baseUri' => 'https://tosvg.com/api/v1', // Default
'timeout' => 30, // Seconds (default: 30)
'maxRetries' => 3, // Retry on 429 (default: 3)
'retryOnRateLimit' => true, // Auto-retry on rate limit (default: true)
],
logger: new Logger('tosvg'), // PSR-3 logger (optional)
);use ToSVG\Data\ImageToSvgOptions;
use ToSVG\Enums\ColorMode;
use ToSVG\Enums\Mode;
// Basic conversion with defaults
$result = $client->convert->imageToSvg('/path/to/image.png');
echo $result->svg; // SVG content string
echo $result->fileSize; // Output file size in bytes
echo $result->conversionTime; // Processing time in seconds
// Save to file
$result->saveTo('/path/to/output.svg');
// Conversion with custom options (named arguments)
$result = $client->convert->imageToSvg('/path/to/image.png', new ImageToSvgOptions(
colorMode: ColorMode::BW,
mode: Mode::Spline,
filterSpeckle: 4,
cornerThreshold: 60,
colorPrecision: 8,
));
// Get supported formats (requires auth)
$formats = $client->convert->supportedFormats();use ToSVG\Data\RemoveBackgroundOptions;
use ToSVG\Enums\Model;
use ToSVG\Enums\Provider;
// Basic background removal (returns file URL)
$result = $client->background->remove('/path/to/photo.jpg');
echo $result->filename; // Output filename
echo $result->path; // Download URL
echo $result->processingTime; // Processing time in seconds
echo $result->provider; // Provider used
// Download the result file
$result->downloadTo('/path/to/output.png');
// With base64 output
$result = $client->background->remove('/path/to/photo.jpg', new RemoveBackgroundOptions(
returnBase64: true,
));
echo $result->image; // Base64-encoded image data
echo $result->format; // Output format
// Save base64 result directly
$result->downloadTo('/path/to/output.png');
// With custom provider and model
$result = $client->background->remove('/path/to/photo.jpg', new RemoveBackgroundOptions(
provider: Provider::Rembg,
model: Model::Silueta,
format: 'jpg',
));
// Get available models
$models = $client->background->models();
// Filter by provider
$models = $client->background->models(Provider::Rembg);use ToSVG\Data\ResizeImageOptions;
// Resize with required dimensions
$result = $client->resize->resize('/path/to/image.png', new ResizeImageOptions(
width: 800,
height: 600,
));
echo $result->path; // Download URL
echo $result->size; // File size in bytes
echo $result->getWidth(); // Actual width
echo $result->getHeight(); // Actual height
echo $result->quality; // Quality used
echo $result->format; // Output format
echo $result->processingTime; // Processing time
// Download the result
$result->downloadTo('/path/to/resized.png');
// With all options
$result = $client->resize->resize('/path/to/image.png', new ResizeImageOptions(
width: 1024,
height: 768,
quality: 75,
format: 'webp',
maintainAspectRatio: false,
));
// Get resize limits
$limits = $client->resize->limits();// Health check (no authentication required)
$health = $client->info->health();
echo $health->status; // "healthy" or "degraded"
echo $health->timestamp; // ISO 8601 timestamp
$health->isHealthy(); // true/false
print_r($health->services); // Service statuses
// API info (no authentication required)
$info = $client->info->apiInfo();The SDK accepts three types of file inputs:
// 1. File path (string)
$result = $client->convert->imageToSvg('/path/to/image.png');
// 2. SplFileInfo
$file = new SplFileInfo('/path/to/image.png');
$result = $client->convert->imageToSvg($file);
// 3. Stream resource (via HttpClient helper)
$stream = fopen('/path/to/image.png', 'r');
$prepared = $client->getHttpClient()->prepareResource($stream);
$result = $client->getHttpClient()->postMultipart('convert/image-to-svg', [
$prepared,
['name' => 'options[color_mode]', 'contents' => 'color'],
]);The SDK uses PHP 8.1 backed enums:
use ToSVG\Enums\ColorMode; // ColorMode::Color, ColorMode::BW
use ToSVG\Enums\Mode; // Mode::Polygon, Mode::Spline
use ToSVG\Enums\Provider; // Provider::Rembg, Provider::WithoutBg
use ToSVG\Enums\Model; // Model::U2Net, Model::Silueta,
// Model::U2NetHumanSeg, Model::IsnetGeneralUseThe SDK throws specific exceptions for each error type:
use ToSVG\Exceptions\AuthenticationException;
use ToSVG\Exceptions\BadRequestException;
use ToSVG\Exceptions\ForbiddenException;
use ToSVG\Exceptions\NetworkException;
use ToSVG\Exceptions\RateLimitException;
use ToSVG\Exceptions\ServerException;
use ToSVG\Exceptions\ToSVGException;
use ToSVG\Exceptions\ValidationException;
try {
$result = $client->convert->imageToSvg('/path/to/image.png');
} catch (AuthenticationException $e) {
// 401 — Invalid, expired, or missing API key
echo "Auth error: {$e->getMessage()}";
echo "Error code: {$e->errorCode}"; // MISSING_API_KEY, INVALID_API_KEY, etc.
} catch (ForbiddenException $e) {
// 403 — IP restricted or subscription required
echo "Forbidden: {$e->getMessage()}";
} catch (ValidationException $e) {
// 422 — Field validation errors
echo "Validation: {$e->getMessage()}";
foreach ($e->errors as $field => $messages) {
echo "{$field}: " . implode(', ', $messages);
}
// Helper methods
$e->hasFieldErrors('image'); // true/false
$e->getFieldErrors('image'); // ['The image field is required.']
} catch (BadRequestException $e) {
// 400 — UNSUPPORTED_FORMAT, FILE_TOO_LARGE, VALIDATION_ERROR
echo "Bad request: {$e->errorCode}";
} catch (RateLimitException $e) {
// 429 — Rate limit exceeded
echo "Rate limited. Retry after: {$e->retryAfter}s";
echo "Limit: {$e->limit}, Window: {$e->window}";
} catch (ServerException $e) {
// 500/502/503/504 — Server errors (may have non-JSON body for 502-504)
echo "Server error (HTTP {$e->statusCode}): {$e->getMessage()}";
} catch (NetworkException $e) {
// Connection failures, timeouts, DNS errors
echo "Network error: {$e->getMessage()}";
} catch (ToSVGException $e) {
// Base class — catches all ToSVG errors
echo "Error: {$e->getMessage()} (HTTP {$e->statusCode})";
}Rate limit info is automatically parsed from response headers:
// Make an API call
$result = $client->convert->imageToSvg('/path/to/image.png');
// Check rate limit status
$rateLimit = $client->getRateLimitInfo();
if ($rateLimit !== null) {
echo "Limit: {$rateLimit->limit}"; // Daily limit
echo "Remaining: {$rateLimit->remaining}"; // Remaining requests
echo "Resets at: {$rateLimit->getResetDate()->format('Y-m-d H:i:s')}";
echo "Seconds until reset: {$rateLimit->getSecondsUntilReset()}";
echo "Exhausted: " . ($rateLimit->isExhausted() ? 'yes' : 'no');
}The SDK automatically retries requests when rate limited (HTTP 429):
- Checks response body
retry_afterfield (highest priority) - Falls back to
Retry-Afterresponse header - Falls back to 60 seconds default
Configure retry behavior:
$client = new ToSVGClient('your-api-key', [
'retryOnRateLimit' => true, // Enable/disable auto-retry (default: true)
'maxRetries' => 3, // Maximum retry attempts (default: 3)
]);The API uses snake_case parameters. The SDK converts these to PHP camelCase:
| API Parameter | SDK Property |
|---|---|
color_mode |
colorMode |
filter_speckle |
filterSpeckle |
corner_threshold |
cornerThreshold |
color_precision |
colorPrecision |
return_base64 |
returnBase64 |
maintain_aspect_ratio |
maintainAspectRatio |
processing_time |
processingTime |
file_size |
fileSize |
MIT License. See LICENSE for details.