How to generate text and images using Google Gemini

Let’s build a simple function that will use curl to accept a prompt and display a response from Gemini that will bring back both a text answer and a dynamically generated image.

Prerequisites

To create an API key you will need to go to https://aistudio.google.com/app/u/1/apikey and click on Create API key

If you have a pre-existing project in your Google Cloud projects you can use the search bar to select it.

Alternatively, you can create an API key by clicking the blue Create API key in new project.

Copy the API key that is generated and displayed on screen.

Now create your project folder. We can call this folder gemini-tutor for testing.

Create your index.php file and add the following code. Paste your API key into the GEMINI_API_KEY definition. Note that Gemini offers different models depending on your needs or preferences. You can take a look at the currently available models in Google AI Studio over here

Today we’re using the 2.0 flash preview image model.

<?php

$geminiApiKey = "your api key here";

$apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-preview-image-generation:generateContent?key=" . $geminiApiKey;

$postData = [
    "contents" => [
        [
            "parts" => [
                [
                    "text" => "Create a butterfly in a cute realistic animated chibi style landing on a flower. Do not include any text or labels.  No words, numbers, or overlay text."
                ]
            ]
        ]
    ],
    "generationConfig" => ["responseModalities" => ["Text", "Image"]]
];

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
    exit;
}

curl_close($ch);
print '<pre>';
print_r($response);
// Extract base64 encoded image data
if (preg_match('/"data": "([^"]*)"/', $response, $matches)) {
    $base64ImageData = $matches[1];
    $imageData = base64_decode($base64ImageData);

    if ($imageData !== false) {
        file_put_contents('gemini-native-image.png', $imageData);
        echo "Image saved as gemini-native-image.png\n";
    } else {
        echo "Failed to decode base64 image data.\n";
    }
} else {
    echo "Image data not found in response.\n";
    echo "Response: " . $response . "\n"; 
}

?>

This will produce and save an image and a caption similar to the following:

A vibrant, cute, realistically styled animated chibi butterfly with large, expressive eyes and intricately patterned wings is gently touching down on a bright, cheerful flower with soft, rounded petals. The scene should evoke a sense of gentle beauty and charm, emphasizing the delicate interaction between the insect and the blossom.



Leave a Reply