Membuat Video dari Gambar menggunakan Veo

Buat video dari gambar, menggunakan Veo , model AI generatif untuk pembuatan video.

Mempelajari lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Go Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"
	"time"

	"google.golang.org/genai"
)

// generateVideoFromImage shows how to gen video from img.
func generateVideoFromImage(w io.Writer, outputGCSURI string) error {
	//outputGCSURI = "gs://your-bucket/your-prefix"
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	image := &genai.Image{
		GCSURI:   "gs://cloud-samples-data/generative-ai/image/flowers.png",
		MIMEType: "image/png",
	}

	config := &genai.GenerateVideosConfig{
		AspectRatio:  "16:9",
		OutputGCSURI: outputGCSURI,
	}

	modelName := "veo-3.0-generate-preview"
	prompt := "Extreme close-up of a cluster of vibrant wildflowers swaying gently in a sun-drenched meadow."
	operation, err := client.Models.GenerateVideos(ctx, modelName, prompt, image, config)
	if err != nil {
		return fmt.Errorf("failed to start video generation: %w", err)
	}

	// Polling until the operation is done
	for !operation.Done {
		time.Sleep(15 * time.Second)
		operation, err = client.Operations.GetVideosOperation(ctx, operation, nil)
		if err != nil {
			return fmt.Errorf("failed to get operation status: %w", err)
		}
	}

	if operation.Response != nil && len(operation.Response.GeneratedVideos) > 0 {
		videoURI := operation.Response.GeneratedVideos[0].Video.URI
		fmt.Fprintln(w, videoURI)
		return nil
	}

	// Example response:
	// gs://your-bucket/your-prefix/videoURI

	return fmt.Errorf("video generation failed or returned no results")
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.genai.Client;
import com.google.genai.types.GenerateVideosConfig;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GenerateVideosResponse;
import com.google.genai.types.GeneratedVideo;
import com.google.genai.types.GetOperationConfig;
import com.google.genai.types.Image;
import com.google.genai.types.Video;
import java.util.concurrent.TimeUnit;

public class VideoGenWithImg {

  public static void main(String[] args) throws InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "veo-3.0-generate-preview";
    String outputGcsUri = "gs://your-bucket/your-prefix";
    generateContent(modelId, outputGcsUri);
  }

  // Generates a video with an image and a text prompt.
  public static String generateContent(String modelId, String outputGcsUri)
      throws InterruptedException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client = Client.builder().location("global").vertexAI(true).build()) {

      GenerateVideosOperation operation =
          client.models.generateVideos(
              modelId,
              "Extreme close-up of a cluster of vibrant wildflowers"
                  + " swaying gently in a sun-drenched meadow.",
              Image.builder()
                  .gcsUri("gs://cloud-samples-data/generative-ai/image/flowers.png")
                  .mimeType("image/png")
                  .build(),
              GenerateVideosConfig.builder()
                  .aspectRatio("16:9")
                  .outputGcsUri(outputGcsUri)
                  .build());

      while (!operation.done().orElse(false)) {
        TimeUnit.SECONDS.sleep(15);
        operation =
            client.operations.getVideosOperation(operation, GetOperationConfig.builder().build());
      }

      String generatedVideoUri =
          operation
              .response()
              .flatMap(GenerateVideosResponse::generatedVideos)
              .flatMap(videos -> videos.stream().findFirst())
              .flatMap(GeneratedVideo::video)
              .flatMap(Video::uri)
              .orElseThrow(
                  () ->
                      new IllegalStateException(
                          "Could not get the URI from the generated video"));

      System.out.println("Generated video URI: " + generatedVideoUri);
      // Example response:
      // Generated video URI: gs://your-bucket/your-prefix/generated-video-123.mp4
      return generatedVideoUri;
    }
  }
}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Node.js Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

const {GoogleGenAI} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function generateVideo(
  outputGcsUri,
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  let operation = await client.models.generateVideos({
    model: 'veo-3.1-fast-generate-001',
    prompt:
      'Extreme close-up of a cluster of vibrant wildflowers swaying gently in a sun-drenched meadow',
    image: {
      gcsUri: 'gs://cloud-samples-data/generative-ai/image/flowers.png',
      mimeType: 'image/png',
    },
    config: {
      aspectRatio: '16:9',
      outputGcsUri: outputGcsUri,
    },
  });

  while (!operation.done) {
    await new Promise(resolve => setTimeout(resolve, 15000));
    operation = await client.operations.get({operation: operation});
    console.log(operation);
  }

  if (operation.response) {
    console.log(operation.response.generatedVideos[0].video.uri);
  }
  return operation;
}

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import time
from google import genai
from google.genai.types import GenerateVideosConfig, Image

client = genai.Client()

# TODO(developer): Update and un-comment below line
# output_gcs_uri = "gs://your-bucket/your-prefix"

operation = client.models.generate_videos(
    model="veo-3.1-generate-001",
    prompt="Extreme close-up of a cluster of vibrant wildflowers swaying gently in a sun-drenched meadow.",
    image=Image(
        gcs_uri="gs://cloud-samples-data/generative-ai/image/flowers.png",
        mime_type="image/png",
    ),
    config=GenerateVideosConfig(
        aspect_ratio="16:9",
        output_gcs_uri=output_gcs_uri,
    ),
)

while not operation.done:
    time.sleep(15)
    operation = client.operations.get(operation)
    print(operation)

if operation.response:
    print(operation.result.generated_videos[0].video.uri)

# Example response:
# gs://your-bucket/your-prefix

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat Google Cloud browser contoh.