This sample demonstrates how to use the Imagen model to generate an image from text.

## Code sample

### C#


Before trying this sample, follow the C# setup instructions in the
[Vertex AI quickstart using
client libraries](https://docs.cloud.google.com/vertex-ai/docs/start/client-libraries).


For more information, see the
[Vertex AI C# API
reference documentation](https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest).


To authenticate to Vertex AI, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    using https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.html;
    using System;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;

    public class GenerateImage
    {
        public async Task<FileInfo> Generate(
            string projectId = "your-project-id")
        {
            var predictionServiceClient = new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.PredictionServiceClientBuilder.html
            {
                Endpoint = "us-central1-aiplatform.googleapis.com"
            }.Build();

            string prompt = "a dog reading a newspaper";
            string outputFileName = "dog_newspaper.png";
            string location = "us-central1";
            string model = "gemini-2.5-flash-image";

            var generateContentRequest = new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.GenerateContentRequest.html
            {
                Model = $"projects/{projectId}/locations/{location}/publishers/google/models/{model}",
                Contents =
                {
                    new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.Content.html
                    {
                        Role = "USER",
                        Parts = 
                        { 
                            new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.Part.html { Text = prompt } 
                        }
                    }
                }
            };

            https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.GenerateContentResponse.html response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

            var imagePart = response.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.GenerateContentResponse.html#Google_Cloud_AIPlatform_V1_GenerateContentResponse_Candidates.FirstOrDefault()?.Content?.Parts?.FirstOrDefault(p => p.InlineData != null);

            if (imagePart == null)
            {
                throw new Exception("No image data was returned by the model.");
            }

            byte[] imageBytes = imagePart.InlineData.Data.ToByteArray();

            https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.AIPlatform.V1/latest/Google.Cloud.AIPlatform.V1.GoogleDriveSource.Types.ResourceId.Types.ResourceType.html#Google_Cloud_AIPlatform_V1_GoogleDriveSource_Types_ResourceId_Types_ResourceType_File.WriteAllBytes(outputFileName, imageBytes);
            FileInfo fileInfo = new FileInfo(Path.GetFullPath(outputFileName));

            Console.WriteLine($"Created output image {fileInfo.FullName} with {fileInfo.Length} bytes");
            return fileInfo;
        }
    }

### Java


Before trying this sample, follow the Java setup instructions in the
[Vertex AI quickstart using
client libraries](https://docs.cloud.google.com/vertex-ai/docs/start/client-libraries).


For more information, see the
[Vertex AI Java API
reference documentation](https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1).


To authenticate to Vertex AI, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    import com.google.api.gax.rpc.https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ApiException.html;
    import com.google.cloud.aiplatform.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.EndpointName.html;
    import com.google.cloud.aiplatform.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictResponse.html;
    import com.google.cloud.aiplatform.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictionServiceClient.html;
    import com.google.cloud.aiplatform.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictionServiceSettings.html;
    import com.google.gson.Gson;
    import com.google.protobuf.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.InvalidProtocolBufferException.html;
    import com.google.protobuf.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html;
    import com.google.protobuf.util.https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.Base64;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;

    public class GenerateImageSample {

      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "my-project-id";
        String location = "us-central1";
        String prompt = ""; // The text prompt describing what you want to see.

        generateImage(projectId, location, prompt);
      }

      // Generate an image using a text prompt using an Imagen model
      public static https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictResponse.html generateImage(String projectId, String location, String prompt)
          throws https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ApiException.html, IOException {
        final String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
        https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictionServiceSettings.html predictionServiceSettings =
            https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictionServiceSettings.html.newBuilder().setEndpoint(endpoint).build();

        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictionServiceClient.html predictionServiceClient =
            https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictionServiceClient.html.create(predictionServiceSettings)) {

          final https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.EndpointName.html endpointName =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.EndpointName.html.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.EndpointName.html#com_google_cloud_aiplatform_v1_EndpointName_ofProjectLocationPublisherModelName_java_lang_String_java_lang_String_java_lang_String_java_lang_String_(
                  projectId, location, "google", "imagen-3.0-generate-001");

          Map<String, Object> instancesMap = new HashMap<>();
          instancesMap.put("prompt", prompt);
          https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html instances = mapToValue(instancesMap);

          Map<String, Object> paramsMap = new HashMap<>();
          paramsMap.put("sampleCount", 1);
          // You can't use a seed value and watermark at the same time.
          // paramsMap.put("seed", 100);
          // paramsMap.put("addWatermark", false);
          paramsMap.put("aspectRatio", "1:1");
          paramsMap.put("safetyFilterLevel", "block_some");
          paramsMap.put("personGeneration", "allow_adult");
          https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html parameters = mapToValue(paramsMap);

          https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictResponse.html predictResponse =
              predictionServiceClient.predict(
                  endpointName, Collections.singletonList(instances), parameters);

          for (https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html prediction : predictResponse.https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.PredictResponse.html#com_google_cloud_aiplatform_v1_PredictResponse_getPredictionsList__()) {
            Map<String, Value> fieldsMap = prediction.getStructValue().getFieldsMap();
            if (fieldsMap.containsKey("bytesBase64Encoded")) {
              String bytesBase64Encoded = fieldsMap.get("bytesBase64Encoded").getStringValue();
              Path tmpPath = Files.createTempFile("imagen-", ".png");
              Files.write(tmpPath, Base64.getDecoder().decode(bytesBase64Encoded));
              System.out.format("Image file written to: %s\n", tmpPath.toUri());
            }
          }
          return predictResponse;
        }
      }

      private static https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html mapToValue(Map<String, Object> map) throws https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.InvalidProtocolBufferException.html {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html.Builder builder = https://docs.cloud.google.com/java/docs/reference/google-cloud-aiplatform/latest/com.google.cloud.aiplatform.v1.Value.html.newBuilder();
        https://docs.cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html.parser().merge(json, builder);
        return builder.build();
      }
    }

### Node.js


Before trying this sample, follow the Node.js setup instructions in the
[Vertex AI quickstart using
client libraries](https://docs.cloud.google.com/vertex-ai/docs/start/client-libraries).


For more information, see the
[Vertex AI Node.js API
reference documentation](https://docs.cloud.google.com/nodejs/docs/reference/aiplatform/latest).


To authenticate to Vertex AI, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    /**
     * TODO(developer): Update these variables before running the sample.
     */
    const projectId = process.env.CAIP_PROJECT_ID;
    const location = 'us-central1';
    const prompt = 'a dog reading a newspaper';

    const aiplatform = require('https://docs.cloud.google.com/nodejs/docs/reference/aiplatform/latest/overview.html');

    // Imports the Google Cloud Prediction Service Client library
    const {PredictionServiceClient} = aiplatform.v1;

    // Import the helper module for converting arbitrary protobuf.Value objects
    const {helpers} = aiplatform;

    // Specifies the location of the api endpoint
    const clientOptions = {
      apiEndpoint: `${location}-aiplatform.googleapis.com`,
    };

    // Instantiates a client
    const predictionServiceClient = new https://docs.cloud.google.com/nodejs/docs/reference/aiplatform/latest/overview.html(clientOptions);

    async function generateImage() {
      const fs = require('fs');
      const util = require('util');
      // Configure the parent resource
      const endpoint = `projects/${projectId}/locations/${location}/publishers/google/models/imagen-3.0-generate-001`;

      const promptText = {
        prompt: prompt, // The text prompt describing what you want to see
      };
      const instanceValue = https://docs.cloud.google.com/nodejs/docs/reference/aiplatform/latest/overview.html.toValue(promptText);
      const instances = [instanceValue];

      const parameter = {
        sampleCount: 1,
        // You can't use a seed value and watermark at the same time.
        // seed: 100,
        // addWatermark: false,
        aspectRatio: '1:1',
        safetyFilterLevel: 'block_some',
        personGeneration: 'allow_adult',
      };
      const parameters = https://docs.cloud.google.com/nodejs/docs/reference/aiplatform/latest/overview.html.toValue(parameter);

      const request = {
        endpoint,
        instances,
        parameters,
      };

      // Predict request
      const [response] = await predictionServiceClient.predict(request);
      const predictions = response.predictions;
      if (predictions.length === 0) {
        console.log(
          'No image was generated. Check the request parameters and prompt.'
        );
      } else {
        let i = 1;
        for (const prediction of predictions) {
          const buff = Buffer.from(
            prediction.structValue.fields.bytesBase64Encoded.stringValue,
            'base64'
          );
          // Write image content to the output file
          const writeFile = util.promisify(fs.writeFile);
          const filename = `output${i}.png`;
          await writeFile(filename, buff);
          console.log(`Saved image ${filename}`);
          i++;
        }
      }
    }
    await generateImage();

### Python


Before trying this sample, follow the Python setup instructions in the
[Vertex AI quickstart using
client libraries](https://docs.cloud.google.com/vertex-ai/docs/start/client-libraries).


For more information, see the
[Vertex AI Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/aiplatform/latest).


To authenticate to Vertex AI, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    import https://docs.cloud.google.com/python/docs/reference/vertexai/latest
    from vertexai.preview.vision_models import https://docs.cloud.google.com/python/docs/reference/vertexai/latest/vertexai.preview.vision_models.ImageGenerationModel.html

    # TODO(developer): Update and un-comment below lines
    # PROJECT_ID = "your-project-id"
    # output_file = "input-image.png"
    # prompt = "" # The text prompt describing what you want to see.

    https://docs.cloud.google.com/python/docs/reference/vertexai/latest.init(project=PROJECT_ID, location="us-central1")

    model = https://docs.cloud.google.com/python/docs/reference/vertexai/latest/vertexai.preview.vision_models.ImageGenerationModel.html.https://docs.cloud.google.com/python/docs/reference/vertexai/latest/vertexai.preview.vision_models.ImageGenerationModel.html#vertexai_preview_vision_models_ImageGenerationModel_from_pretrained("imagen-3.0-generate-002")

    images = model.https://docs.cloud.google.com/python/docs/reference/vertexai/latest/vertexai.preview.vision_models.ImageGenerationModel.html#vertexai_preview_vision_models_ImageGenerationModel_generate_images(
        prompt=prompt,
        # Optional parameters
        number_of_images=1,
        language="en",
        # You can't use a seed value and watermark at the same time.
        # add_watermark=False,
        # seed=100,
        aspect_ratio="1:1",
        safety_filter_level="block_some",
        person_generation="allow_adult",
    )

    images[0].save(location=output_file, include_generation_parameters=False)

    # Optional. View the generated image in a notebook.
    # images[0].show()

    print(f"Created output image using {len(images[0]._image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=generativeaionvertexai).