๐จ DeepAI Image Colorizer: Bringing Life to Black & White Photos with .NET
๐ Introduction
In the digital age, we often encounter historical photographs, vintage images, or artistic black and white compositions that we'd love to see in full color. While professional colorization requires significant artistic skill and time, modern AI has democratized this process. Today, we'll explore a .NET console application that leverages the DeepAI Colorization API to automatically transform grayscale images into vibrant, colorized versions.
๐ฏ The Problem Statement
Colorizing black and white images manually is a time-intensive process that requires:
- Deep understanding of color theory
- Artistic sensibility for appropriate color selection
- Hours of meticulous work in image editing software
For developers and researchers working with large collections of historical images, automated solutions become essential. Our solution provides a programmatic approach to image colorization using cutting-edge AI technology.
๐️ Solution Architecture
The DeepAI Image Colorizer is a lightweight .NET console application that serves as a bridge between local image files and the DeepAI colorization service. The architecture follows clean code principles with separation of concerns:
Core Components
- Program.cs - Entry point and command-line interface
- ImageColorizerHelper.cs - API interaction and image processing logic
- Environment Configuration - Secure API key management
Technology Stack
- Framework: .NET 10.0 with C# 14.0
- Dependencies:
DotNetEnvfor environment variable managementSystem.Net.Httpfor API communication
- External Service: DeepAI Colorization API
๐ป Implementation Details
You can see the source code online on my GitHub repo here:
https://github.com/toreaurstadboss/DeepAIColorizerCommand-Line Interface Design
The application features a clean, user-friendly CLI with comprehensive argument parsing:
static async Task Main(string[] args)
{
// Load environment variables from .env file
Env.Load();
var inputPath = GetArgValue(args, "--input") ?? GetArgValue(args, "-i");
var outputPath = GetArgValue(args, "--output") ?? GetArgValue(args, "-o");
var apiKey = GetArgValue(args, "--apikey") ?? Environment.GetEnvironmentVariable("DEEPAI_API_KEY");
// Display help if no arguments provided
if (args.Length == 0 || args.Contains("--help") || args.Contains("-h"))
{
DisplayHelp();
return;
}
// ... validation and processing logic
}
API Integration Layer
The ImageColorizerHelper class encapsulates all DeepAI API interactions, providing a clean abstraction:
public class ImageColorizerHelper
{
private readonly string _apiKey;
private readonly HttpClient _httpClient;
public ImageColorizerHelper(string apiKey)
{
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new ArgumentException("API key cannot be null or empty.", nameof(apiKey));
}
_apiKey = apiKey;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("api-key", _apiKey);
}
}
Asynchronous Image Processing
The core colorization method handles the complete workflow asynchronously.
The image inputted will be posted as a binary array added in MultipartFormDataContent to the endpoint
where
DeepAI Colorizer service is served.
https://api.deepai.org/api/colorizer - Note - This endpoint is only POST-ed to.
The response is an url (json) that points to where we can download the final colorized picture, if success.
The code shows we post the input image (grayscale image obviously) to colorize:
public async Task ColorizeImageAsync(string inputPath, string outputPath)
{
if (!File.Exists(inputPath))
{
throw new FileNotFoundException($"Input image not found: {inputPath}");
}
// Prepare multipart form data with the image
using var form = new MultipartFormDataContent();
var imageBytes = await File.ReadAllBytesAsync(inputPath);
form.Add(new ByteArrayContent(imageBytes), "image", Path.GetFileName(inputPath));
Console.WriteLine("⏳ Sending image to DeepAI for colorization...");
// Send request to DeepAI API
var response = await _httpClient.PostAsync("https://api.deepai.org/api/colorizer", form);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine($"๐ก Received response from DeepAI");
// Parse JSON response to extract the output URL
var result = JsonDocument.Parse(jsonResponse);
if (!result.RootElement.TryGetProperty("output_url", out var urlElement))
{
throw new InvalidOperationException("DeepAI response missing 'output_url' property.");
}
var outputUrl = urlElement.GetString();
if (string.IsNullOrWhiteSpace(outputUrl))
{
throw new InvalidOperationException("DeepAI returned an empty output URL. The image may have been rejected.");
}
Console.WriteLine($"๐ Output URL: {outputUrl}");
Console.WriteLine("⏳ Downloading colorized image...");
// Download the colorized image
var colorizedBytes = await _httpClient.GetByteArrayAsync(outputUrl);
// Ensure output directory exists
var outputDir = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(outputDir) && !Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
// Save the colorized image
await File.WriteAllBytesAsync(outputPath, colorizedBytes);
Console.WriteLine($"๐พ Saved colorized image ({colorizedBytes.Length:N0} bytes)");
}
๐ง Configuration and Security
Environment-Based API Key Management
The application prioritizes security by supporting multiple API key sources:
var apiKey = GetArgValue(args, "--apikey") ?? Environment.GetEnvironmentVariable("DEEPAI_API_KEY");
This allows users to:
- Store keys in a
.envfile (loaded automatically) - Pass keys via command-line arguments
- Use environment variables in CI/CD pipelines
Project Configuration
The .csproj file demonstrates modern .NET project setup:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>14.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNetEnv" Version="3.1.1" />
<ItemGroup>
</Project>
๐ Usage Examples
Basic Colorization
DeepAIColorizer --input old_photo.jpg --output colorized_photo.png
With Custom API Key
DeepAIColorizer --input image.png --apikey your_deepai_key_here
Batch Processing Integration
The CLI design makes it perfect for batch processing:
for file in *.jpg; do
DeepAIColorizer --input "$file"
done
✨ Key Features and Benefits
๐จ Automated Colorization
- Leverages state-of-the-art AI models trained on millions of images
- Produces natural-looking colors without manual intervention
๐ Security-First Design
- Multiple API key management options
- No hardcoded credentials
- Environment variable support for production deployments
๐ Developer-Friendly
- Clean, documented code following .NET best practices
- Comprehensive error handling and user feedback
- Asynchronous operations for responsive CLI experience
๐ Progress Indicators
- Real-time feedback during processing
- Clear success/error messaging with emojis
- File size reporting for verification
๐ง Extensible Architecture
- Modular design allows easy integration into larger systems
- HTTP client abstraction enables testing and mocking
- Clean separation between CLI and business logic
๐ Technical Analysis
Performance Characteristics
- Network I/O: Two HTTP requests per image (upload + download)
- Memory Usage: Minimal - processes images in streams
- CPU Overhead: Negligible - delegates heavy computation to DeepAI servers
Error Handling Strategy
The application implements comprehensive error handling:
- Input Validation: Checks file existence and API key presence
- API Error Handling: Distinguishes between different HTTP status codes
- Network Resilience: Proper async/await patterns for network operations
- User Feedback: Clear error messages with actionable guidance
Code Quality Metrics
- Cyclomatic Complexity: Low - simple, linear control flow
- Testability: High - dependency injection and interface segregation
- Maintainability: Excellent - clear naming and documentation
๐ Academic Applications
This tool has significant value in academic research:
๐ Historical Research
- Colorizing archival photographs for modern publications
- Enhancing visual materials for academic presentations
- Preserving historical imagery with improved accessibility
๐จ Digital Humanities
- Automated processing of large image collections
- Integration with research workflows and pipelines
- Supporting visual analysis in humanities studies
๐ป Computer Science Education
- Practical example of API integration
- Demonstration of async programming patterns
- Real-world application of software engineering principles
๐ฎ Future Enhancements
Potential improvements for future versions:
- Batch Processing: Support for multiple input files
- Format Conversion: Automatic format detection and conversion
- Quality Options: Different colorization quality levels
- Preview Mode: Generate thumbnails before full processing
- Integration APIs: REST API wrapper for web applications
๐ Conclusion
The DeepAI Image Colorizer represents a perfect intersection of modern AI capabilities and practical software engineering. By abstracting complex machine learning models behind a simple, secure CLI interface, it makes advanced image processing accessible to developers, researchers, and enthusiasts alike.
The implementation demonstrates key software engineering principles: clean architecture, comprehensive error handling, security-conscious design, and excellent user experience. Whether you're a historian bringing old photographs to life or a developer learning API integration, this project serves as both a practical tool and an educational reference.
Ready to colorize your world? ๐ The code is available on GitHub - clone, build, and start transforming black and white images into vibrant masterpieces!
Tips how to get contact the DeepAI Api using Postman
- The request must be of type POST and url set to : https://api.deepai.org/api/colorizer
- Headers - set one header : api-key . The value here is your DeepAI api key and must of course be not compromised.
- Body : Choose form-data as the type of body. Add a key called image.
- Choose the folder icon and connect to a local folder on your hard drive and upload image. This is the image key value under POST.
- You should get a response with a Json with the information where to download the processed image, which is colorized.
{
"id": "exampleGuid1",
"output_url": "https://api.deepai.org/job-view-file/exampleGuid2/outputs/output.jpg"
}
ExampleGuids here will of course vary per run. To download the actual outputted image, just follow the URL. This can actually be done inside Postman.
Example input and output images using the tool
The following examples images shows input and output images using the tool. The scenery is from Trondheim, Norway in 1959. Original photo (grayscale, 1959) :
Colorized photo (DeepAI Image Colorization online API service) using this tool :
