Skip to content

Commit b83001b

Browse files
jdomingrJuan Dominguez
andauthored
feat(genai): add image generation samples (1) (#10172)
* feat(genai): add new image generation samples * fix imggen with text region tag * refactor: improve optional handling by adding a specific exception when using orElseThrow * refactor: change tests and remove cleanup that's not necessary --------- Co-authored-by: Juan Dominguez <[email protected]>
1 parent de522ce commit b83001b

File tree

7 files changed

+250
-0
lines changed

7 files changed

+250
-0
lines changed

genai/snippets/resources/man.png

1.51 MB
Loading
8.06 MB
Loading
2.19 MB
Loading
360 KB
Loading
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package genai.imagegeneration;
18+
19+
// [START googlegenaisdk_imggen_virtual_try_on_with_txt_img]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.GeneratedImage;
23+
import com.google.genai.types.Image;
24+
import com.google.genai.types.ProductImage;
25+
import com.google.genai.types.RecontextImageResponse;
26+
import com.google.genai.types.RecontextImageSource;
27+
import java.awt.image.BufferedImage;
28+
import java.io.ByteArrayInputStream;
29+
import java.io.File;
30+
import java.io.IOException;
31+
import java.nio.file.Files;
32+
import java.nio.file.Paths;
33+
import javax.imageio.ImageIO;
34+
35+
public class ImageGenVirtualTryOnWithTextAndImage {
36+
37+
public static void main(String[] args) throws IOException {
38+
// TODO(developer): Replace these variables before running the sample.
39+
String modelId = "virtual-try-on-preview-08-04";
40+
String outputFile = "resources/output/man_in_sweater.png";
41+
generateContent(modelId, outputFile);
42+
}
43+
44+
// Generates a recontextualized image with image inputs
45+
public static Image generateContent(String modelId, String outputFile) throws IOException {
46+
// Client Initialization. Once created, it can be reused for multiple requests.
47+
try (Client client = Client.builder().location("global").vertexAI(true).build()) {
48+
49+
byte[] personImageBytes = Files.readAllBytes(Paths.get("resources/man.png"));
50+
Image personImage = Image.builder().imageBytes(personImageBytes).build();
51+
52+
byte[] productImageBytes = Files.readAllBytes(Paths.get("resources/sweater.jpg"));
53+
Image productImage = Image.builder().imageBytes(productImageBytes).build();
54+
55+
RecontextImageResponse recontextImageResponse =
56+
client.models.recontextImage(
57+
modelId,
58+
RecontextImageSource.builder()
59+
.personImage(personImage)
60+
.productImages(ProductImage.builder().productImage(productImage).build())
61+
.build(),
62+
null);
63+
64+
Image generatedImage =
65+
recontextImageResponse
66+
.generatedImages()
67+
.flatMap(generatedImages -> generatedImages.stream().findFirst())
68+
.flatMap(GeneratedImage::image)
69+
.orElseThrow(() -> new IllegalStateException("No image was generated by the model."));
70+
71+
// Read image data and write it to the output file
72+
if (generatedImage.imageBytes().isPresent()) {
73+
BufferedImage image =
74+
ImageIO.read(new ByteArrayInputStream(generatedImage.imageBytes().get()));
75+
ImageIO.write(image, "png", new File(outputFile));
76+
77+
System.out.printf(
78+
"Created output image using %s bytes\n", generatedImage.imageBytes().get().length);
79+
}
80+
81+
// Example response:
82+
// Created output image using 1637865 bytes
83+
return generatedImage;
84+
}
85+
}
86+
}
87+
// [END googlegenaisdk_imggen_virtual_try_on_with_txt_img]
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package genai.imagegeneration;
18+
19+
// [START googlegenaisdk_imggen_with_txt]
20+
21+
import com.google.genai.Client;
22+
import com.google.genai.types.GenerateImagesConfig;
23+
import com.google.genai.types.GenerateImagesResponse;
24+
import com.google.genai.types.GeneratedImage;
25+
import com.google.genai.types.Image;
26+
import java.awt.image.BufferedImage;
27+
import java.io.ByteArrayInputStream;
28+
import java.io.File;
29+
import java.io.IOException;
30+
import javax.imageio.ImageIO;
31+
32+
public class ImageGenWithText {
33+
34+
public static void main(String[] args) throws IOException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
String modelId = "imagen-4.0-generate-001";
37+
String outputFile = "resources/output/dog_newspaper.png";
38+
generateImage(modelId, outputFile);
39+
}
40+
41+
// Generates an image with text input
42+
public static Image generateImage(String modelId, String outputFile) throws IOException {
43+
// Client Initialization. Once created, it can be reused for multiple requests.
44+
try (Client client = Client.builder().location("global").vertexAI(true).build()) {
45+
46+
GenerateImagesResponse response =
47+
client.models.generateImages(
48+
modelId,
49+
"A dog reading a newspaper",
50+
GenerateImagesConfig.builder().imageSize("2K").outputMimeType("image/png").build());
51+
52+
Image generatedImage =
53+
response
54+
.generatedImages()
55+
.flatMap(generatedImages -> generatedImages.stream().findFirst())
56+
.flatMap(GeneratedImage::image)
57+
.orElseThrow(() -> new IllegalStateException("No image was generated by the model."));
58+
59+
// Read image data and write it to the output file
60+
if (generatedImage.imageBytes().isPresent()) {
61+
BufferedImage image =
62+
ImageIO.read(new ByteArrayInputStream(generatedImage.imageBytes().get()));
63+
ImageIO.write(image, "png", new File(outputFile));
64+
65+
System.out.printf(
66+
"Created output image using %s bytes\n", generatedImage.imageBytes().get().length);
67+
}
68+
69+
// Example response:
70+
// Created output image using 1633112 bytes
71+
return generatedImage;
72+
}
73+
}
74+
}
75+
// [END googlegenaisdk_imggen_with_txt]
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package genai.imagegeneration;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static com.google.common.truth.Truth.assertWithMessage;
21+
22+
import com.google.genai.types.Image;
23+
import java.io.ByteArrayOutputStream;
24+
import java.io.File;
25+
import java.io.IOException;
26+
import java.io.PrintStream;
27+
import org.junit.After;
28+
import org.junit.AfterClass;
29+
import org.junit.Before;
30+
import org.junit.BeforeClass;
31+
import org.junit.Test;
32+
import org.junit.runner.RunWith;
33+
import org.junit.runners.JUnit4;
34+
35+
@RunWith(JUnit4.class)
36+
public class ImageGenerationIT {
37+
38+
private static final String IMAGGEN_4_MODEL = "imagen-4.0-generate-001";
39+
private static final String VIRTUAL_TRY_ON_MODEL = "virtual-try-on-preview-08-04";
40+
41+
private ByteArrayOutputStream bout;
42+
private PrintStream out;
43+
44+
// Check if the required environment variables are set.
45+
public static void requireEnvVar(String envVarName) {
46+
assertWithMessage(String.format("Missing environment variable '%s' ", envVarName))
47+
.that(System.getenv(envVarName))
48+
.isNotEmpty();
49+
}
50+
51+
@BeforeClass
52+
public static void checkRequirements() {
53+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
54+
}
55+
56+
@Before
57+
public void setUp() {
58+
bout = new ByteArrayOutputStream();
59+
out = new PrintStream(bout);
60+
System.setOut(out);
61+
}
62+
63+
@After
64+
public void tearDown() {
65+
System.setOut(null);
66+
}
67+
68+
@Test
69+
public void testImageGenVirtualTryOnWithTextAndImage() throws IOException {
70+
Image image =
71+
ImageGenVirtualTryOnWithTextAndImage.generateContent(
72+
VIRTUAL_TRY_ON_MODEL, "resources/output/man_in_sweater.png");
73+
74+
assertThat(image).isNotNull();
75+
assertThat(image.imageBytes()).isPresent();
76+
assertThat(image.imageBytes().get().length).isGreaterThan(0);
77+
}
78+
79+
@Test
80+
public void testImageGenWithText() throws IOException {
81+
Image image =
82+
ImageGenWithText.generateImage(IMAGGEN_4_MODEL, "resources/output/dog_newspaper.png");
83+
84+
assertThat(image).isNotNull();
85+
assertThat(image.imageBytes()).isPresent();
86+
assertThat(image.imageBytes().get().length).isGreaterThan(0);
87+
}
88+
}

0 commit comments

Comments
 (0)