PHP code example of minhyung / sdwebui

1. Go to this page and download the library: Download minhyung/sdwebui library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

minhyung / sdwebui example snippets


use Minhyung\SdWebUi\SdWebUi;

$sd = SdWebUi::create('http://127.0.0.1:7860');

$sd->txt2img()
    ->prompt('a lighthouse in a storm, dramatic lighting')
    ->negativePrompt('blurry, lowres')
    ->size(768, 512)
    ->steps(30)
    ->send()
    ->first()
    ->saveTo('lighthouse.png');

use GuzzleHttp\Client;

$sd = SdWebUi::create('http://127.0.0.1:7860')
    ->httpClient(new Client(['timeout' => 600]));

use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpClient\HttpClient;

$sd = SdWebUi::create('http://127.0.0.1:7860')
    ->httpClient(new Psr18Client(HttpClient::create([
        'timeout' => 600,       // inactivity timeout
        'max_duration' => 900,  // total ceiling
    ])));

$sd = SdWebUi::create('http://127.0.0.1:7860')->basicAuth('user', 'pass');

use Minhyung\SdWebUi\Enum\Sampler;
use Minhyung\SdWebUi\Enum\Scheduler;

$result = $sd->txt2img()
    ->prompt('a cat sitting on a windowsill, golden hour')
    ->negativePrompt('blurry, lowres, watermark')
    ->size(768, 512)
    ->steps(30)
    ->cfgScale(7.0)
    ->sampler(Sampler::DpmPlusPlus2M)   // or just 'DPM++ 2M'
    ->scheduler(Scheduler::Karras)
    ->seed(12345)
    ->batch(size: 2, iterations: 2)     // four images
    ->send();

foreach ($result as $i => $image) {
    $image->saveTo("out-{$i}.png");
}

$result->info()->seed();          // resolved seed
$result->info()->sdModelName();   // which checkpoint ran
$result->infotextFor(0);          // the reproducible metadata block

$sd->txt2img()
    ->prompt('a detailed landscape')
    ->size(512, 512)
    ->hiresFix(scale: 2.0, upscaler: 'R-ESRGAN 4x+', denoisingStrength: 0.4)
    ->send();

use Minhyung\SdWebUi\Value\Image;

$sd->img2img()
    ->initImage(Image::fromFile('photo.png'))
    ->prompt('an oil painting')
    ->denoisingStrength(0.6)
    ->send();

$sd->img2img()
    ->initImage(Image::fromFile('photo.png'))
    ->mask(Image::fromFile('mask.png'))
    ->prompt('a red hat')
    ->onlyMasked()
    ->inpaintPadding(32)
    ->send();

$sd->txt2img()
    ->prompt('a cat')
    ->checkpoint('sd_xl_base_1.0.safetensors [31e35c80fc]')
    ->clipSkip(2)
    ->send();

$sd->options()->checkpoint('sd_xl_base_1.0.safetensors [31e35c80fc]');

Image::fromFile('in.png');
Image::fromBinary($bytes);
Image::fromBase64($base64OrDataUri);
Image::fromUrl('https://example.com/in.png');   // the server fetches it

$image->saveTo('out.png');
$image->toBinary();
$image->toBase64();     // bare base64 — what the API wants
$image->format();       // sniffed from magic bytes
$image->dimensions();

$sd->extras()
    ->image(Image::fromFile('small.png'))
    ->upscaler('R-ESRGAN 4x+')
    ->scaleBy(2.0)
    ->send()
    ->first()
    ->saveTo('large.png');

$sd->extrasBatch()
    ->add(Image::fromFile('a.png'), 'a.png')
    ->add(Image::fromFile('b.png'), 'b.png')
    ->upscaler('R-ESRGAN 4x+')
    ->scaleBy(2.0)
    ->send();

$info = $sd->pngInfo(Image::fromFile('generated.png'));

$info->prompt();
$info->seed();
$info->infotext();

// Reproduce it
$sd->txt2img()->infotext($info->infotext())->send();

$sd->txt2img()->infotext($info->infotext())->styles([])->send();

use Minhyung\SdWebUi\Script\ADetailerUnit;
use Minhyung\SdWebUi\Script\ControlNetUnit;

$sd->txt2img()
    ->prompt('a person standing in a field')
    ->controlNet(fn (ControlNetUnit $u) => $u
        ->module('canny')
        ->model('control_v11p_sd15_canny [d14c016b]')
        ->image(Image::fromFile('pose.png'))
        ->weight(1.0)
        ->guidance(0.0, 0.8)
        ->pixelPerfect())
    ->adetailer(fn (ADetailerUnit $u) => $u
        ->model('face_yolov8n.pt')
        ->denoisingStrength(0.4))
    ->send();

$sd->scripts()->find('controlnet');       // labels, defaults, ranges, choices
$sd->scripts()->argumentCount('adetailer');

$sd->txt2img()->prompt('a cat')->alwaysOn('MyExtension', [true, 0.5])->send();
$sd->txt2img()->prompt('a cat')->script('X/Y/Z plot', [/* ... */])->send();

$request = $sd->txt2img()->prompt('a cat')->steps(50);
$taskId = $request->taskId();   // hand this to another process

$request->send();

$progress = $sd->progress()->task($taskId);

$progress->percent();       // 42
$progress->eta();           // seconds
$progress->livePreview();   // ?Image
$progress->isFinished();
$progress->isUnknown();     // the server has no record of this id

use Symfony\Component\HttpClient\HttplugClient;

$sd = SdWebUi::create('http://127.0.0.1:7860')
    ->httpClient(new HttplugClient());

$sd->txt2img()
    ->prompt('a cat')
    ->steps(50)
    ->onProgress(function ($progress) {
        echo $progress->percent() . "%\n";
    }, intervalMs: 500)
    ->send();

$sd->catalog()->sdModelTitles();   // ['v1-5-pruned.safetensors [abc123]', ...]
$sd->catalog()->upscalerNames();
$sd->options()->samplesFormat();
$sd->progress()->interrupt();

try {
    $sd->catalog()->sdModels();
} catch (AuthenticationException $e) {   // wrong --api-auth credentials
} catch (TransportException $e) {        // host unreachable
}

use Minhyung\SdWebUi\Exception\ApiException;
use Minhyung\SdWebUi\Exception\SdWebUiException;
use Minhyung\SdWebUi\Exception\TransportException;
use Minhyung\SdWebUi\Exception\ValidationException;

try {
    $sd->txt2img()->prompt('a cat')->send();
} catch (ValidationException $e) {
    foreach ($e->violations() as $violation) {
        echo implode('.', $violation['loc']) . ': ' . $violation['message'] . "\n";
    }
} catch (ApiException $e) {
    $e->statusCode();
    $e->detail();
} catch (TransportException $e) {
    // Never reached the server: connection refused, or a timeout.
} catch (SdWebUiException $e) {
    // Anything this SDK throws.
}

$sd->raw()->post('/my-extension/v1/thing', ['a' => 1]);
$sd->raw()->get('/my-extension/v1/status');

$sd->txt2img()->prompt('a cat')->with('some_new_field', 42)->send();

final class GuardedClient implements \Psr\Http\Client\ClientInterface
{
    public function __construct(private \Psr\Http\Client\ClientInterface $inner) {}

    public function sendRequest(\Psr\Http\Message\RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        // assert on $request->getUri()->getHost(), start a span, count a metric...
        return $this->inner->sendRequest($request);
    }
}

$sd = SdWebUi::create('http://127.0.0.1:7860')->httpClient(new GuardedClient($psr18Client));

$sd = SdWebUi::create('http://127.0.0.1:7860')->logger($psrLogger);

$sd->logger($psrLogger)->debugLogging(false);
bash
composer config allow-plugins.php-http/discovery true
composer