API documentation

Image Pig is a REST API running at api.imagepig.com, you just send a JSON HTTP request and get back a JSON with base64 encoded data containing an image. Alternatively, we can store the generated image for you – this feature is available only in some paid plans.

Text prompts (text to image)

Using text prompts, we generate an image based on your text input. There is a positive and a negative prompt that guide AI model what to (and what not to) generate. The only limitation is your imagination.

We offer three endpoints based on different models:

# Default text prompt

You just send a HTTP POST request to https://api.imagepig.com/, include your API key in the request header and add JSON payload with your text prompt.

The endpoint generates images using the Realistic Vision V5.1 model (licensed under CreativeML Open RAIL-M), which is based on Stable Diffusion 1.5 (SD1.5) base model. Output image size for SD1.5 models is 512×512 px.

The SD1.5 models are relatively fast – under normal conditions, we generate the response in one or two seconds.

Technical specification

Endpoint: /
HTTP method: POST
Request headers
Content-Type (string, required) application/json
Api-Key (string, required) your-api-key
Request body attributes
positive_prompt or prompt (string) Text guiding image generation. Basically, you put here what you want to see on the generated image.
negative_prompt (string) Opposite of positive_prompt. You can specify here what you do not want to see on the generated image.
format (string, default: JPEG) Output image format. It can be either JPEG or PNG.
seed (non-negative 64-bit integer, default: random value) Seed is a starting point for the random number generator used by model to generate images. Set it if you want to get deterministic results.
storage_days (non-negative integer, default: 0) Return image_url with uploaded file URL (instead of returning image_data). The URL will be valid for several days, depending on the storage_days value, then the file will be removed. When set to 0, this feature is disabled. Available only in some plans.
Response body attributes (success)
image_data (string) A base64 encoded AI generated image.
image_url (string) In case of sending storage_days, image URL is returned instead of image_data.
mime_type (string) MIME type of the image, based on the format request attribute. It can be either image/jpeg or image/png.
seed (non-negative 64-bit integer) A seed value used for generating this particular image.
started_at (string) ISO-formatted date and time of when the API started to process the request.
completed_at (string) ISO-formatted date and time of when the API finished with generating the image.
Response body attributes (error)
error (string) An error message explaining what went wrong.
started_at (string) ISO-formatted date and time of when the API started to process the request.
completed_at (string) ISO-formatted date and time of when the API responded with the error message.

Usage examples

For Python, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the pip package manager:

pip install imagepig

Then, use this package to call the API:

from imagepig import ImagePig

imagepig = ImagePig("your-api-key")
result = imagepig.default("adorable pig")
result.save("adorable-pig.jpeg")

And that is all you need to do. Only one import and three lines of code!

Alternatively, if you prefer to write the code for accessing the API by yourself, you can use the requests library to get our generated image from Image Pig:

from base64 import b64decode
from pathlib import Path

import requests

r = requests.post(
    "https://api.imagepig.com/",
    headers={"Api-Key": "your-api-key"},
    json={"prompt": "adorable pig"},
)

if r.ok:
    with Path("adorable-pig.jpeg").open("wb") as f:
        f.write(b64decode(r.json()["image_data"]))
else:
    r.raise_for_status()

For JavaScript (or TypeScript, if your project allows JavaScript modules) based on Node.js, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the npm package manager:

npm i imagepig

Then, use this package to call the API:

const ImagePig = require('imagepig');

void async function() {
    const imagepig = ImagePig('your-api-key');
    const result = await imagepig.default('adorable pig')
    await result.save('adorable-pig.jpeg');
}();

And that is all you need to do.

Alternatively, if you prefer to write the code for accessing the API by yourself, you can retrieve the generated image using the Fetch API and create a file with Node.js's fs and Buffer modules.

const fs = require('node:fs');
const { Buffer } = require('node:buffer');

void async function() {
    try {
        response = await fetch('https://api.imagepig.com/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Api-Key': 'your-api-key'
            },
            body: JSON.stringify({"prompt": "adorable pig"})
        });

        if (!response.ok) {
            throw new Error(`Response status: ${response.status}`);
        }

        json = await response.json();
        const buffer = Buffer.from(json.image_data, 'base64');

        fs.writeFile(
            'adorable-pig.jpeg',
            buffer,
            (error) => {
                if (error) {
                    throw error;
                }
            }
        );
    } catch (error) {
        console.error(error);
    }
}();

For PHP, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the composer dependency manager:

composer require doubleplus/imagepig

Then, use this package to call the API:

<?php

$imagepig = ImagePig\ImagePig('your-api-key');
$result = $imagepig->default('adorable pig');
$result->save('adorable-pig.jpeg');

And that is all you need to do. Only the opening tag and three lines of code!

Alternatively, if you prefer to write the code for accessing the API by yourself, you can use the cURL library to get the generated image from Image Pig.

<?php

$ch = curl_init('https://api.imagepig.com/');

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Api-Key: your-api-key',
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'prompt' => 'adorable pig',
]));

$response = curl_exec($ch);

if (curl_errno($ch)) {
    exit('Error: ' . curl_error($ch));
}

$handle = fopen('adorable-pig.jpeg', 'wb');
fwrite($handle, base64_decode(json_decode($response, true)['image_data']));
fclose($handle);

For this Rust example, we will need to install some dependencies using cargo first:

cargo add base64
cargo add reqwest -F json
cargo add serde -F derive
cargo add tokio -F rt-multi-thread -F macros

Then, we are able to run it using the cargo run command.

use base64::Engine;

#[derive(serde::Deserialize)]
struct ImagePigResponse {
    image_data: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let response = client.post("https://api.imagepig.com/")
        .header("Content-Type", "application/json")
        .header("Api-Key", "your-api-key")
        .body(r#"{"prompt": "adorable pig"}"#)
        .send()
        .await?;

    response.error_for_status_ref()?;

    let json = response.json::<ImagePigResponse>().await?;
    let content = base64::prelude::BASE64_STANDARD.decode(json.image_data)?;

    std::fs::write("adorable-pig.jpeg", content).unwrap();

    Ok(())
}

Anyway, the code will write the resulting image a to a file named adorable-pig.jpeg, which looks like this:

adorable pig

Try it out!

You need to have an API key to use this functionality. Create your Image Pig account or log in.

# XL text prompt

XL text prompt is similar to the default text prompt, except that it is send to the https://api.imagepig.com/xl URL.

The endpoint generates images using the RealVisXL V5.0 model (licensed under CreativeML Open RAIL++-M), which is based on Stable Diffusion XL (SDXL) base model. As the name suggests, the output image size of SDXL models is extra large, which means 1024×1024 px.

The SDXL models are little slower than SD1.5 models – under normal conditions, we generate the response within three or four seconds.

Technical specification

Endpoint: /xl
HTTP method: POST
Request headers
Content-Type (string, required) application/json
Api-Key (string, required) your-api-key
Request body attributes
positive_prompt or prompt (string) Text guiding image generation. Basically, you put here what you want to see on the generated image.
negative_prompt (string) Opposite of positive_prompt. You can specify here what you do not want to see on the generated image.
format (string, default: JPEG) Output image format. It can be either JPEG or PNG.
seed (non-negative 64-bit integer, default: random value) Seed is a starting point for the random number generator used by model to generate images. Set it if you want to get deterministic results.
storage_days (non-negative integer, default: 0) Return image_url with uploaded file URL (instead of returning image_data). The URL will be valid for several days, depending on the storage_days value, then the file will be removed. When set to 0, this feature is disabled. Available only in some plans.
Response body attributes (success)
image_data (string) A base64 encoded AI generated image.
image_url (string) In case of sending storage_days, image URL is returned instead of image_data.
mime_type (string) MIME type of the image, based on the format request attribute. It can be either image/jpeg or image/png.
seed (non-negative 64-bit integer) A seed value used for generating this particular image.
started_at (string) ISO-formatted date and time of when the API started to process the request.
completed_at (string) ISO-formatted date and time of when the API finished with generating the image.
Response body attributes (error)
error (string) An error message explaining what went wrong.
started_at (string) ISO-formatted date and time of when the API started to process the request.
completed_at (string) ISO-formatted date and time of when the API responded with the error message.

Usage examples

For Python, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the pip package manager:

pip install imagepig

Then, use this package to call the API:

from imagepig import ImagePig

imagepig = ImagePig("your-api-key")
result = imagepig.xl("sunbathing pig")
result.save("sunbathing-pig.jpeg")

And that is all you need to do. Only one import and three lines of code!

Alternatively, if you prefer to write the code for accessing the API by yourself, you can use the requests library to get our generated image from Image Pig:

from base64 import b64decode
from pathlib import Path

import requests

r = requests.post(
    "https://api.imagepig.com/xl",
    headers={"Api-Key": "your-api-key"},
    json={"prompt": "happy sunbathing pig, resting"},
)

if r.ok:
    with Path("sunbathing-pig.jpeg").open("wb") as f:
        f.write(b64decode(r.json()["image_data"]))
else:
    r.raise_for_status()

For JavaScript (or TypeScript, if your project allows JavaScript modules) based on Node.js, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the npm package manager:

npm i imagepig

Then, use this package to call the API:

const ImagePig = require('imagepig');

void async function() {
    const imagepig = ImagePig('your-api-key');
    const result = await imagepig.xl('sunbathing pig')
    await result.save('sunbathing-pig.jpeg');
}();

And that is all you need to do.

Alternatively, if you prefer to write the code for accessing the API by yourself, you can retrieve the generated image using the Fetch API and create a file with Node.js's fs and Buffer modules.

const fs = require('node:fs');
const { Buffer } = require('node:buffer');

void async function() {
    try {
        response = await fetch('https://api.imagepig.com/xl', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Api-Key': 'your-api-key'
            },
            body: JSON.stringify({"prompt": "happy sunbathing pig, resting"})
        });

        if (!response.ok) {
            throw new Error(`Response status: ${response.status}`);
        }

        json = await response.json();
        const buffer = Buffer.from(json.image_data, 'base64');

        fs.writeFile(
            'sunbathing-pig.jpeg',
            buffer,
            (error) => {
                if (error) {
                    throw error;
                }
            }
        );
    } catch (error) {
        console.error(error);
    }
}();

For PHP, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the composer dependency manager:

composer require doubleplus/imagepig

Then, use this package to call the API:

<?php

$imagepig = ImagePig\ImagePig('your-api-key');
$result = $imagepig->xl('sunbathing pig');
$result->save('sunbathing-pig.jpeg');

And that is all you need to do. Only the opening tag and three lines of code!

Alternatively, if you prefer to write the code for accessing the API by yourself, you can use the cURL library to get the generated image from Image Pig.

<?php

$ch = curl_init('https://api.imagepig.com/xl');

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Api-Key: your-api-key',
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'prompt' => 'happy sunbathing pig, resting',
]));

$response = curl_exec($ch);

if (curl_errno($ch)) {
    exit('Error: ' . curl_error($ch));
}

$handle = fopen('sunbathing-pig.jpeg', 'wb');
fwrite($handle, base64_decode(json_decode($response, true)['image_data']));
fclose($handle);

For this Rust example, we will need to install some dependencies using cargo first:

cargo add base64
cargo add reqwest -F json
cargo add serde -F derive
cargo add tokio -F rt-multi-thread -F macros

Then, we are able to run it using the cargo run command.

use base64::Engine;

#[derive(serde::Deserialize)]
struct ImagePigResponse {
    image_data: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let response = client.post("https://api.imagepig.com/xl")
        .header("Content-Type", "application/json")
        .header("Api-Key", "your-api-key")
        .body(r#"{"prompt": "happy sunbathing pig, resting"}"#)
        .send()
        .await?;

    response.error_for_status_ref()?;

    let json = response.json::<ImagePigResponse>().await?;
    let content = base64::prelude::BASE64_STANDARD.decode(json.image_data)?;

    std::fs::write("sunbathing-pig.jpeg", content).unwrap();

    Ok(())
}

Anyway, the code will write the resulting image a to a file named sunbathing-pig.jpeg, which looks like this:

sunbathing pig

Try it out!

You need to have an API key to use this functionality. Create your Image Pig account or log in.

# FLUX text prompt

FLUX model is different than stable diffusion models: for example, there is no negative_prompt. The request is send to the https://api.imagepig.com/flux URL.

The endpoint generates images using the FLUX.1 [schnell] model (licensed under Apache License 2.0). We consider this model to be a state-of-the-art technology, as it is able to render very complicated text prompts and even manages to display writing acceptably. It produces reasonably SFW images.

The FLUX model is much slower than stable diffusion models – even under normal conditions, it can take more than five seconds to generate an image.

Using this endpoint is computationally demanding, so each image generated counts as two standard API calls.

Output image size of this model is variable and it can be set in the payload. By default, we render images in a landscape mode (i.e. 1216×832 px).

Technical specification

Endpoint: /flux
HTTP method: POST
Request headers
Content-Type (string, required) application/json
Api-Key (string, required) your-api-key
Request body attributes
positive_prompt or prompt (string) Text guiding image generation. Basically, you put here what you want to see on the generated image.
proportion (string, default: landscape) The dimension of output image. You can enter one of following values:
  • landscape – 1216×832 px
  • portrait – 832×1216 px
  • square – 1024×1024 px
  • wide – 1344×768 px
format (string, default: JPEG) Output image format. It can be either JPEG or PNG.
seed (non-negative 64-bit integer, default: random value) Seed is a starting point for the random number generator used by model to generate images. Set it if you want to get deterministic results.
storage_days (non-negative integer, default: 0) Return image_url with uploaded file URL (instead of returning image_data). The URL will be valid for several days, depending on the storage_days value, then the file will be removed. When set to 0, this feature is disabled. Available only in some plans.
Response body attributes (success)
image_data (string) A base64 encoded AI generated image.
image_url (string) In case of sending storage_days, image URL is returned instead of image_data.
mime_type (string) MIME type of the image, based on the format request attribute. It can be either image/jpeg or image/png.
seed (non-negative 64-bit integer) A seed value used for generating this particular image.
started_at (string) ISO-formatted date and time of when the API started to process the request.
completed_at (string) ISO-formatted date and time of when the API finished with generating the image.
Response body attributes (error)
error (string) An error message explaining what went wrong.
started_at (string) ISO-formatted date and time of when the API started to process the request.
completed_at (string) ISO-formatted date and time of when the API responded with the error message.

Usage examples

For Python, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the pip package manager:

pip install imagepig

Then, use this package to call the API:

from imagepig import ImagePig

imagepig = ImagePig("your-api-key")
result = imagepig.flux("space captain pig")
result.save("space-captain-pig.jpeg")

And that is all you need to do. Only one import and three lines of code!

Alternatively, if you prefer to write the code for accessing the API by yourself, you can use the requests library to get our generated image from Image Pig:

from base64 import b64decode
from pathlib import Path

import requests

r = requests.post(
    "https://api.imagepig.com/flux",
    headers={"Api-Key": "your-api-key"},
    json={"prompt": "a pig as a pilot of a cosmic ship, floating in a space"},
)

if r.ok:
    with Path("space-captain-pig.jpeg").open("wb") as f:
        f.write(b64decode(r.json()["image_data"]))
else:
    r.raise_for_status()

For JavaScript (or TypeScript, if your project allows JavaScript modules) based on Node.js, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the npm package manager:

npm i imagepig

Then, use this package to call the API:

const ImagePig = require('imagepig');

void async function() {
    const imagepig = ImagePig('your-api-key');
    const result = await imagepig.flux('space captain pig')
    await result.save('space-captain-pig.jpeg');
}();

And that is all you need to do.

Alternatively, if you prefer to write the code for accessing the API by yourself, you can retrieve the generated image using the Fetch API and create a file with Node.js's fs and Buffer modules.

const fs = require('node:fs');
const { Buffer } = require('node:buffer');

void async function() {
    try {
        response = await fetch('https://api.imagepig.com/flux', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Api-Key': 'your-api-key'
            },
            body: JSON.stringify({"prompt": "a pig as a pilot of a cosmic ship, floating in a space"})
        });

        if (!response.ok) {
            throw new Error(`Response status: ${response.status}`);
        }

        json = await response.json();
        const buffer = Buffer.from(json.image_data, 'base64');

        fs.writeFile(
            'space-captain-pig.jpeg',
            buffer,
            (error) => {
                if (error) {
                    throw error;
                }
            }
        );
    } catch (error) {
        console.error(error);
    }
}();

For PHP, we provide a convenient imagepig package that you can use to easily access the API.

First, install it using the composer dependency manager:

composer require doubleplus/imagepig

Then, use this package to call the API:

<?php

$imagepig = ImagePig\ImagePig('your-api-key');
$result = $imagepig->flux('space captain pig');
$result->save('space-captain-pig.jpeg');

And that is all you need to do. Only the opening tag and three lines of code!

Alternatively, if you prefer to write the code for accessing the API by yourself, you can use the cURL library to get the generated image from Image Pig.

<?php

$ch = curl_init('https://api.imagepig.com/flux');

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Api-Key: your-api-key',
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'prompt' => 'a pig as a pilot of a cosmic ship, floating in a space',
]));

$response = curl_exec($ch);

if (curl_errno($ch)) {
    exit('Error: ' . curl_error($ch));
}

$handle = fopen('space-captain-pig.jpeg', 'wb');
fwrite($handle, base64_decode(json_decode($response, true)['image_data']));
fclose($handle);

For this Rust example, we will need to install some dependencies using cargo first:

cargo add base64
cargo add reqwest -F json
cargo add serde -F derive
cargo add tokio -F rt-multi-thread -F macros

Then, we are able to run it using the cargo run command.

use base64::Engine;

#[derive(serde::Deserialize)]
struct ImagePigResponse {
    image_data: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let response = client.post("https://api.imagepig.com/flux")
        .header("Content-Type", "application/json")
        .header("Api-Key", "your-api-key")
        .body(r#"{"prompt": "a pig as a pilot of a cosmic ship, floating in a space"}"#)
        .send()
        .await?;

    response.error_for_status_ref()?;

    let json = response.json::<ImagePigResponse>().await?;
    let content = base64::prelude::BASE64_STANDARD.decode(json.image_data)?;

    std::fs::write("space-captain-pig.jpeg", content).unwrap();

    Ok(())
}

Anyway, the code will write the resulting image a to a file named space-captain-pig.jpeg, which looks like this:

space captain pig

Try it out!

You need to have an API key to use this functionality. Create your Image Pig account or log in.

Do you miss any functionality? Did you get lost in our reference? Or something does not work as expected? Contact us and our AI image effect specialist will help you to implement a solution according to your needs.