Generate an image with ChatGPT
Part 4 is dedicated to generating an image via ChatGPT using its “dall-e-3” model. The image will be generated programmatically. Once generated, we'll retrieve the URL so that we can insert it into an HTML page. We'll do this in PHP.
Code: generateImage()
function generateImage( $material )
{
$apiKey = 'YOUR_API_KEY'
$url = 'https://api.openai.com/v1/images/generations';
$data = [ 'prompt' => $material ,
'model' => 'dall-e-3' ,
'n' => 1 ,
'quality' => 'hd' ,
'style' => 'natural' ,
'size' => '1024x1024' ,
];
$ch = curl_init($url);
curl_setopt( $ch,CURLOPT_URL , $url);
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch,CURLOPT_POST , true);
curl_setopt( $ch,CURLOPT_POSTFIELDS , json_encode( $data ) );
curl_setopt( $ch,CURLOPT_HTTPHEADER , [ 'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
] );
$result = curl_exec( $ch );
curl_close($ch);
$response = json_decode( $result,true );
if ( isset( $response['error'] ) )
{
return ( null );
}
else
{
return ( $response['data'][0]['url'] );
}
}
The function takes 1 parameter : $material
$material is the prompt to create your image. Example: "Generate an ultra-realistic image of a futuristic web radio studio. It's painted in shades of deep red and white. A South Asian female radio host is doing her show, fully immersed in her work. The room is filled with highly detailed and sophisticated broadcasting equipment, which includes microphones, headphones, control panels, and computer screens. The overall setting has a modern futuristic vibe."
The function is called by the following code:
$material = "Generate an ultra-realistic image of a futuristic web radio studio. It's painted in shades of deep red and white. A South Asian female radio host is doing her show, fully immersed in her work. The room is filled with highly detailed and sophisticated broadcasting equipment, which includes microphones, headphones, control panels, and computer screens. The overall setting has a modern futuristic vibe.";
// No error handling in this simple example
echo "<p><img src='" . generateImage( $material ) . "' /></p>;
The result has been a URL that points to the image that got just created:
领英推荐
This is also the image I used to illustrate this article.
Of course ...
This call to ChatGPT presupposes your have already an account and an API Key, which is precisely the subject covered in the second article of this series.
Conclusion
We have one more weapon in our arsenal: we can generate images programmatically by invoking ChatGPT. Our function's code is written in PHP, but you'll have no trouble transforming it into Python, node.js, JavaScript, etc.
See you soon for more examples and ... above all ... no complications: keep things simple, but no simpler than they need to be.