luc118.c (2271B)
1 /* 2 * Author : Amit Dutta <amitdutta4255@gmail.com> 3 * Date : 08 Feb 2026 4 * Repo : https://github.com/notamitgamer/bsc 5 * License : MIT License (See the LICENSE file for details) 6 */ 7 8 /* Write a program to generate 4 images of birds flying in the sky with a computer's mouse in their beak using OpenAI Image API. 9 */ 10 /* Let Us C, Chap- 24 (Interaction with ChatGPT through C), Qn No.: B(b) */ 11 12 /* This file is auto-generated by a bot. */ 13 /* This code is not compiled; it is for reference only. */ 14 15 /* NOTE: These programs require the 'libcurl' library to compile. 16 Command: gcc luc118.c -o output -lcurl */ 17 18 19 #include <stdio.h> 20 #include <stdlib.h> 21 #include <string.h> 22 #include <curl/curl.h> 23 24 /* Pre-requisites: 25 1. Install libcurl. 26 2. Get OpenAI API Key. 27 */ 28 29 #define API_KEY "YOUR_OPENAI_API_KEY_HERE" 30 31 int main(void) { 32 CURL *curl; 33 CURLcode res; 34 35 const char *url = "https://api.openai.com/v1/images/generations"; 36 37 // JSON Payload: 4 images, 1024x1024 38 const char *data = "{" 39 "\"prompt\": \"Birds flying in the sky with a computer mouse in their beak\"," 40 "\"n\": 4," 41 "\"size\": \"1024x1024\"" 42 "}"; 43 44 struct curl_slist *headers = NULL; 45 char auth_header[100]; 46 sprintf(auth_header, "Authorization: Bearer %s", API_KEY); 47 48 curl = curl_easy_init(); 49 if(curl) { 50 headers = curl_slist_append(headers, "Content-Type: application/json"); 51 headers = curl_slist_append(headers, auth_header); 52 53 curl_easy_setopt(curl, CURLOPT_URL, url); 54 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); 55 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 56 57 // For simplicity, we print the JSON response to stdout. 58 // The response will contain URLs to the generated images. 59 printf("Sending request to OpenAI Image API...\n\n"); 60 res = curl_easy_perform(curl); 61 62 if(res != CURLE_OK) 63 fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); 64 65 printf("\n\nCheck the JSON output above for 'url' fields to view images.\n"); 66 67 curl_slist_free_all(headers); 68 curl_easy_cleanup(curl); 69 } 70 return 0; 71 }