Skip to content

Official PHP SDK for the toSVG API. Image to SVG conversion, SVG optimization, and background removal for PHP applications.

Notifications You must be signed in to change notification settings

ToSVG/tosvg-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ToSVG PHP SDK

Official PHP SDK for the ToSVG API — Convert images to SVG, remove backgrounds, and resize images.

PHP Version License

Requirements

Installation

composer require tosvg/tosvg-php

Quick Start

use 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;

Authentication

Your API key has the format tosvg_{live|test}_<32-char-random-string>:

  • tosvg_live_ — Production key
  • tosvg_test_ — Sandbox key
$client = new ToSVGClient('tosvg_live_your_api_key');

Configuration

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)
);

Usage

Image to SVG Conversion

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();

Background Removal

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);

Image Resize

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 & API Info

// 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();

File Input Types

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'],
]);

Enums

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::IsnetGeneralUse

Error Handling

The 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 Information

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');
}

Retry Logic

The SDK automatically retries requests when rate limited (HTTP 429):

  1. Checks response body retry_after field (highest priority)
  2. Falls back to Retry-After response header
  3. 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)
]);

Parameter Naming Convention

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

License

MIT License. See LICENSE for details.

About

Official PHP SDK for the toSVG API. Image to SVG conversion, SVG optimization, and background removal for PHP applications.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages