Create Stunning Images with the Image Generation and Inpainting API

10 May 2025
Create Stunning Images with the Image Generation and Inpainting API

The Image Generation and Inpainting API provides developers with powerful tools for creating high-quality images tailored to specific needs. With customizable parameters, this API enables rapid image generation and modification, simplifying workflows for designers, artists, and content creators. Whether you're looking to generate original artwork, enhance existing images, or perform inpainting to fill in missing parts of a picture, this API offers a versatile solution.

Use Cases

  1. Content Creation: Generate unique visuals for blogs, articles, or social media posts without needing extensive design skills.
  2. Artistic Projects: Artists can use the API to draft concepts or create fully realized artworks based on detailed prompts.
  3. E-commerce: Online retailers can generate product images or modify existing ones to better showcase items.
  4. Game Development: Game developers can create assets or modify images to fit specific game environments or themes.

Before diving into the API, ensure you have a Cognitive Actions API key and a basic understanding of making API calls.

Generate Image with Custom Parameters

This action allows you to create high-quality images using a customizable image generation process. You can adjust parameters such as inference steps, image size, aspect ratio, and model choice. It also supports optional image inpainting, fast mode optimizations, and LoRA strength adjustments to enhance your outputs.

Input Requirements

  • Prompt: A detailed description to guide the image generation process (required).
  • Mask/Image: Optional; for inpainting or image-to-image transformations.
  • Model Choice: Select between 'dev' or 'schnell' models for different performance levels.
  • Width/Height: Dimensions for the image, if using a custom aspect ratio.
  • Megapixels: Specify the image size in megapixels.
  • Output Count: Number of images to generate.
  • Fast Mode: Enable for quicker predictions.
  • Guidance Scale: Adjust for more realistic images.
  • Output Quality: Scale from 0 to 100 to determine the fidelity of the output.
  • Additional parameters: Such as LoRA strength, prompt strength, and more for fine-tuning.

Expected Output

The API will return URLs to the generated images in the specified format (e.g., webp, jpg).

Use Cases for This Action

  • Marketing Campaigns: Quickly generate tailored images for ads or promotional materials.
  • Personal Projects: Create custom art pieces based on personal prompts or styles.
  • Rapid Prototyping: Develop concepts for visual projects without needing extensive resources.
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "7f786947-d98c-40b2-bc6e-0a2d4a502e0d" # Action ID for: Generate Image with Custom Parameters

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "model": "dev",
  "prompt": "nath1  studio portrait of a modestly dressed woman in a crisp white blouse, exuding calm elegance, captured in a close-up shot. Her expression is serene and graceful, with soft facial features and neatly long styled hair. Set against a warm beige-brown studio backdrop, the colors create a gentle, harmonious contrast with her white attire. The background is softly blurred to maintain focus on her face and upper shoulders. Subtle side lighting adds dimension to her features, with a soft glow enhancing her natural complexion. Drawn with: fashion editorial studio photography, cinematic close-up, soft lighting, Canon EOS R6, 85mm lens, aperture f/2.2, ISO 100, shutter speed 1/125s, ultra-high resolution, depth of field, realistic skin tone rendering.",
  "megapixels": "1",
  "outputCount": 1,
  "useFastMode": false,
  "loraStrength": 1,
  "guidanceScale": 3,
  "outputQuality": 80,
  "promptStrength": 1,
  "imageAspectRatio": "1:1",
  "imageOutputFormat": "webp",
  "inferenceStepCount": 34,
  "additionalLoraStrength": 1
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")

Conclusion

The Image Generation and Inpainting API streamlines the process of creating and modifying images, making it an invaluable tool for developers across various industries. Its flexibility and customization options allow for a wide range of applications, from content creation to artistic endeavors. Start leveraging this API to enhance your projects and bring your visual ideas to life!