RubyLearning

Helping Ruby Programmers become Awesome!

Programmatically Generate AI Images with Ruby

January 2, 2026 | By RubyLearning

AI image generation has become an essential tool for modern web applications. Whether you're building an e-commerce platform that needs product mockups, a content management system requiring featured images, or a social app with custom avatars, programmatic image generation can save countless hours and provide unlimited creative possibilities.

In this tutorial, we'll explore how to integrate AI image generation into your Ruby applications using a scalable, API-driven approach. We'll use the AI Photo Generator API, which provides a simple REST interface for generating high-quality images from text prompts.

Why Programmatic Image Generation?

Manual image creation doesn't scale. When your application needs to generate hundreds or thousands of unique images—product variations, user content, marketing materials—you need an automated solution. AI image generation APIs offer several advantages:

  • Scalability — Generate images on-demand without designer bottlenecks
  • Consistency — Maintain brand aesthetics through carefully crafted prompts
  • Speed — Get results in seconds rather than hours or days
  • Cost-effectiveness — Pay only for what you generate
  • Customization — Tailor each image to specific requirements programmatically

Getting Started with the API

First, you'll need to obtain an API token from AI Photo Generator. Once you have your token, you can start making requests to generate images.

The API accepts a JSON payload with the following parameters:

  • prompt — The text description of the image you want to generate
  • width — Image width in pixels (e.g., 1024)
  • height — Image height in pixels (e.g., 1024)
  • model — The AI model to use (e.g., "flux-1")
  • count — Number of images to generate

Basic Ruby Implementation

Let's start with a simple implementation using Ruby's built-in net/http library:

require 'net/http'
require 'json'
require 'uri'

def generate_image(prompt, width: 1024, height: 1024, model: 'flux-1', count: 1)
  uri = URI('https://www.aiphotogenerator.net/api/images/generate')

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.path)
  request['Authorization'] = "Bearer #{ENV['AI_PHOTO_GENERATOR_TOKEN']}"
  request['Content-Type'] = 'application/json'

  request.body = {
    prompt: prompt,
    width: width,
    height: height,
    model: model,
    count: count
  }.to_json

  response = http.request(request)

  case response
  when Net::HTTPSuccess
    JSON.parse(response.body)
  else
    raise "API request failed: #{response.code} - #{response.body}"
  end
end

# Example usage
result = generate_image(
  "A professional headshot of a business executive in a modern office"
)
puts result

A More Robust Client Class

For production applications, you'll want a more robust implementation with error handling, retries, and configuration options:

require 'net/http'
require 'json'
require 'uri'

class AIImageGenerator
  API_ENDPOINT = 'https://www.aiphotogenerator.net/api/images/generate'.freeze
  DEFAULT_MODEL = 'flux-1'.freeze
  MAX_RETRIES = 3

  class APIError < StandardError; end
  class RateLimitError < APIError; end

  def initialize(api_token: ENV['AI_PHOTO_GENERATOR_TOKEN'])
    @api_token = api_token
    raise ArgumentError, 'API token is required' unless @api_token
  end

  def generate(prompt, options = {})
    width = options.fetch(:width, 1024)
    height = options.fetch(:height, 1024)
    model = options.fetch(:model, DEFAULT_MODEL)
    count = options.fetch(:count, 1)

    payload = {
      prompt: prompt,
      width: width,
      height: height,
      model: model,
      count: count
    }

    make_request(payload)
  end

  def generate_product_image(product_name, style: 'professional', background: 'white')
    prompt = "#{style} product photography of #{product_name}, #{background} background, studio lighting, high resolution"
    generate(prompt)
  end

  def generate_avatar(description, style: 'realistic')
    prompt = "#{style} portrait, #{description}, professional headshot, neutral background"
    generate(prompt, width: 512, height: 512)
  end

  private

  def make_request(payload, retries: 0)
    uri = URI(API_ENDPOINT)
    http = build_http_client(uri)
    request = build_request(uri, payload)

    response = http.request(request)
    handle_response(response)
  rescue RateLimitError => e
    if retries < MAX_RETRIES
      sleep_time = 2 ** retries
      sleep(sleep_time)
      make_request(payload, retries: retries + 1)
    else
      raise e
    end
  end

  def build_http_client(uri)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.open_timeout = 10
    http.read_timeout = 60
    http
  end

  def build_request(uri, payload)
    request = Net::HTTP::Post.new(uri.path)
    request['Authorization'] = "Bearer #{@api_token}"
    request['Content-Type'] = 'application/json'
    request['User-Agent'] = 'Ruby AI Image Generator Client'
    request.body = payload.to_json
    request
  end

  def handle_response(response)
    case response
    when Net::HTTPSuccess
      JSON.parse(response.body, symbolize_names: true)
    when Net::HTTPTooManyRequests
      raise RateLimitError, 'Rate limit exceeded'
    else
      raise APIError, "Request failed: #{response.code} - #{response.body}"
    end
  end
end

Usage Examples

Here's how you might use the client in different scenarios:

# Initialize the client
client = AIImageGenerator.new

# Generate a custom image
result = client.generate(
  "A serene Japanese garden with cherry blossoms and a koi pond",
  width: 1920,
  height: 1080
)

# Generate product images for an e-commerce site
products = ['leather wallet', 'wireless headphones', 'ceramic mug']
products.each do |product|
  image = client.generate_product_image(product, style: 'minimalist')
  puts "Generated image for #{product}: #{image[:url]}"
end

# Generate user avatars
avatar = client.generate_avatar(
  "friendly woman with glasses, short brown hair",
  style: 'illustrated'
)
puts "Avatar URL: #{avatar[:url]}"

Integration with Rails

In a Rails application, you might create a service object and use Active Job for background processing:

# app/services/image_generation_service.rb
class ImageGenerationService
  def initialize
    @client = AIImageGenerator.new
  end

  def generate_for_product(product)
    result = @client.generate_product_image(product.name)
    product.update(ai_image_url: result[:url])
    result
  end
end

# app/jobs/generate_product_image_job.rb
class GenerateProductImageJob < ApplicationJob
  queue_as :default

  def perform(product_id)
    product = Product.find(product_id)
    ImageGenerationService.new.generate_for_product(product)
  end
end

# In your controller or model
GenerateProductImageJob.perform_later(product.id)

Best Practices

When integrating AI image generation into your Ruby applications, keep these best practices in mind:

  • Use environment variables — Never hardcode API tokens in your source code
  • Implement caching — Cache generated images to avoid redundant API calls
  • Handle errors gracefully — Implement retries and fallbacks for API failures
  • Use background jobs — Image generation can take several seconds; don't block your web requests
  • Monitor usage — Track API calls to manage costs and detect issues
  • Craft good prompts — The quality of your output depends heavily on your prompts

Conclusion

Programmatic AI image generation opens up powerful possibilities for Ruby applications. With just a few lines of code, you can integrate sophisticated image generation capabilities that would have required extensive manual work or expensive design resources in the past.

The AI Photo Generator API provides a straightforward way to add this functionality to your projects. Whether you're building a small side project or a large-scale production application, the patterns shown in this tutorial will help you get started quickly and scale effectively.

Have questions about integrating AI image generation into your Ruby project? Share your use cases and challenges in the comments!

Tags: Ruby AI Image Generation API Rails