PHPackages                             tosvg/tosvg-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. tosvg/tosvg-php

ActiveLibrary[API Development](/categories/api)

tosvg/tosvg-php
===============

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

v1.0.0(3mo ago)10MITPHPPHP ^8.1

Since Feb 6Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/ToSVG/tosvg-php)[ Packagist](https://packagist.org/packages/tosvg/tosvg-php)[ Docs](https://tosvg.com)[ RSS](/packages/tosvg-tosvg-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

ToSVG PHP SDK
=============

[](#tosvg-php-sdk)

Official PHP SDK for the [ToSVG API](https://tosvg.com) — Convert images to SVG, remove backgrounds, and resize images.

[![PHP Version](https://camo.githubusercontent.com/04744bae0a61d2ffe29c26f07a9612eae20445fc6feaeb77b3af1f0e9be6447c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d3838393242462e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Composer
- A ToSVG API key ([Get one here](https://tosvg.com))

Installation
------------

[](#installation)

```
composer require tosvg/tosvg-php
```

Quick Start
-----------

[](#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
--------------

[](#authentication)

Your API key has the format `tosvg_{live|test}_`:

- `tosvg_live_` — Production key
- `tosvg_test_` — Sandbox key

```
$client = new ToSVGClient('tosvg_live_your_api_key');
```

Configuration
-------------

[](#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
-----

[](#usage)

### Image to SVG Conversion

[](#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

[](#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

[](#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 &amp; API Info

[](#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
----------------

[](#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
-----

[](#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
--------------

[](#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-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
-----------

[](#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
---------------------------

[](#parameter-naming-convention)

The API uses `snake_case` parameters. The SDK converts these to PHP `camelCase`:

API ParameterSDK 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
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance81

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

100d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1f27848a0d08b1e165b294b64bb9c3a73ad630c37d553a693e67dd24e506169f?d=identicon)[dege](/maintainers/dege)

---

Top Contributors

[![ertugruldege](https://avatars.githubusercontent.com/u/26246843?v=4)](https://github.com/ertugruldege "ertugruldege (1 commits)")

---

Tags

apisdkconvertimageresizesvgtosvgbackground-removal

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tosvg-tosvg-php/health.svg)

```
[![Health](https://phpackages.com/badges/tosvg-tosvg-php/health.svg)](https://phpackages.com/packages/tosvg-tosvg-php)
```

###  Alternatives

[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.5k311.5k5](/packages/theodo-group-llphant)[mailchimp/transactional

458.9M16](/packages/mailchimp-transactional)[justcommunication-ru/tinkoff-acquiring-api-client

Tinkoff Acquiring API PHP Client

102.5k](/packages/justcommunication-ru-tinkoff-acquiring-api-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
