Hintergrund für Produktbilder generieren
Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Merchant API-Codebeispiel zum Generieren des Hintergrunds für Produktbilder.
Java
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package shopping.merchant.samples.productstudio.v1alpha;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.productstudio.v1alpha.GenerateImageBackgroundConfig;
import com.google.shopping.merchant.productstudio.v1alpha.GenerateProductImageBackgroundRequest;
import com.google.shopping.merchant.productstudio.v1alpha.GenerateProductImageBackgroundResponse;
import com.google.shopping.merchant.productstudio.v1alpha.ImageServiceClient;
import com.google.shopping.merchant.productstudio.v1alpha.ImageServiceSettings;
import com.google.shopping.merchant.productstudio.v1alpha.InputImage;
import com.google.shopping.merchant.productstudio.v1alpha.OutputImageConfig;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to create product images with generated backgrounds. */
public class GenerateProductImageBackgroundSample {
private static String getName(String accountId) {
return String.format("accounts/%s", accountId);
}
public static void generateProductImageBackground(Config config, String imageUri)
throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
ImageServiceSettings imageServiceSettings =
ImageServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
String name = getName(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (ImageServiceClient imageServiceClient = ImageServiceClient.create(imageServiceSettings)) {
OutputImageConfig outputImageConfig =
// Set this field to false to return the image bytes in the response instead.
OutputImageConfig.newBuilder().setReturnImageUri(true).build();
InputImage inputImage =
InputImage.newBuilder()
// You can also use image bytes here instead of a URI.
.setImageUri(imageUri)
.build();
GenerateImageBackgroundConfig generateImageBackgroundConfig =
GenerateImageBackgroundConfig.newBuilder()
.setProductDescription("a jar")
.setBackgroundDescription(
"sitting on a cracked stone surface surrounded by a cherry blossom tree and pink"
+ " and white flowers in the background, high resolution, product"
+ " photography, strong shadows and lights, creative")
.build();
GenerateProductImageBackgroundRequest request =
GenerateProductImageBackgroundRequest.newBuilder()
.setName(name)
.setOutputConfig(outputImageConfig)
.setInputImage(inputImage)
.setConfig(generateImageBackgroundConfig)
.build();
System.out.println("Sending GenerateProductImageBackground request: " + name);
GenerateProductImageBackgroundResponse response =
imageServiceClient.generateProductImageBackground(request);
System.out.println("Generated product image background response below:");
System.out.println(response);
} catch (Exception e) {
System.out.println("An error has occurred: ");
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// Replace with your image URI.
String imageUri =
"https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg";
generateProductImageBackground(config, imageUri);
}
}
Python
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This class demonstrates how to create product images with generated backgrounds."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_productstudio_v1alpha import GenerateImageBackgroundConfig
from google.shopping.merchant_productstudio_v1alpha import GenerateProductImageBackgroundRequest
from google.shopping.merchant_productstudio_v1alpha import ImageServiceClient
from google.shopping.merchant_productstudio_v1alpha import InputImage
from google.shopping.merchant_productstudio_v1alpha import OutputImageConfig
# Gets the merchant account ID from the user's configuration.
_ACCOUNT = configuration.Configuration().read_merchant_info()
# The name of the account to which the request is sent.
# Format: accounts/{account}
_NAME = f"accounts/{_ACCOUNT}"
def generate_product_image_background(image_uri: str) -> None:
"""Generates a product image with a custom background.
Args:
image_uri: The URI of the input image.
"""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = ImageServiceClient(credentials=credentials)
# Creates the output config.
# Set `return_image_uri` to False to return the image bytes in the response.
output_config = OutputImageConfig(return_image_uri=True)
# Creates the input image.
# You can also use image bytes here instead of a URI.
input_image = InputImage(image_uri=image_uri)
# Creates the generate image background config.
generate_image_background_config = GenerateImageBackgroundConfig(
product_description="a jar",
background_description=(
"sitting on a cracked stone surface surrounded by a cherry blossom"
" tree and pink and white flowers in the background, high"
" resolution, product photography, strong shadows and lights,"
" creative"
),
)
# Creates the request.
request = GenerateProductImageBackgroundRequest(
name=_NAME,
output_config=output_config,
input_image=input_image,
config=generate_image_background_config,
)
# Makes the request and catches and prints any error messages.
try:
print(f"Sending GenerateProductImageBackground request: {_NAME}")
response = client.generate_product_image_background(request=request)
print("Generated product image background response below:")
print(response)
except RuntimeError as e:
print("Request failed.")
print(e)
if __name__ == "__main__":
# The URI of the image to use as the base for the generation.
# Replace with your image URI.
_IMAGE_URI = (
"https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg"
)
generate_product_image_background(_IMAGE_URI)
Sofern nicht anders angegeben, sind die Inhalte dieser Seite unter der Creative Commons Attribution 4.0 License und Codebeispiele unter der Apache 2.0 License lizenziert. Weitere Informationen finden Sie in den Websiterichtlinien von Google Developers. Java ist eine eingetragene Marke von Oracle und/oder seinen Partnern.
Zuletzt aktualisiert: 2025-08-21 (UTC).
[null,null,["Zuletzt aktualisiert: 2025-08-21 (UTC)."],[],[],null,["# Generate product image background\n\nMerchant API code sample to generate product image background. \n\n### Java\n\n // Copyright 2025 Google LLC\n //\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.productstudio.v1alpha;\n\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.productstudio.v1alpha.GenerateImageBackgroundConfig;\n import com.google.shopping.merchant.productstudio.v1alpha.GenerateProductImageBackgroundRequest;\n import com.google.shopping.merchant.productstudio.v1alpha.GenerateProductImageBackgroundResponse;\n import com.google.shopping.merchant.productstudio.v1alpha.ImageServiceClient;\n import com.google.shopping.merchant.productstudio.v1alpha.ImageServiceSettings;\n import com.google.shopping.merchant.productstudio.v1alpha.InputImage;\n import com.google.shopping.merchant.productstudio.v1alpha.OutputImageConfig;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to create product images with generated backgrounds. */\n public class GenerateProductImageBackgroundSample {\n\n private static String getName(String accountId) {\n return String.format(\"accounts/%s\", accountId);\n }\n\n public static void generateProductImageBackground(Config config, String imageUri)\n throws Exception {\n // Obtains OAuth token based on the user's configuration.\n GoogleCredentials credential = new Authenticator().authenticate();\n\n ImageServiceSettings imageServiceSettings =\n ImageServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n String name = getName(config.getAccountId().toString());\n\n // Calls the API and catches and prints any network failures/errors.\n try (ImageServiceClient imageServiceClient = ImageServiceClient.create(imageServiceSettings)) {\n\n OutputImageConfig outputImageConfig =\n // Set this field to false to return the image bytes in the response instead.\n OutputImageConfig.newBuilder().setReturnImageUri(true).build();\n\n InputImage inputImage =\n InputImage.newBuilder()\n // You can also use image bytes here instead of a URI.\n .setImageUri(imageUri)\n .build();\n\n GenerateImageBackgroundConfig generateImageBackgroundConfig =\n GenerateImageBackgroundConfig.newBuilder()\n .setProductDescription(\"a jar\")\n .setBackgroundDescription(\n \"sitting on a cracked stone surface surrounded by a cherry blossom tree and pink\"\n + \" and white flowers in the background, high resolution, product\"\n + \" photography, strong shadows and lights, creative\")\n .build();\n\n GenerateProductImageBackgroundRequest request =\n GenerateProductImageBackgroundRequest.newBuilder()\n .setName(name)\n .setOutputConfig(outputImageConfig)\n .setInputImage(inputImage)\n .setConfig(generateImageBackgroundConfig)\n .build();\n\n System.out.println(\"Sending GenerateProductImageBackground request: \" + name);\n GenerateProductImageBackgroundResponse response =\n imageServiceClient.generateProductImageBackground(request);\n System.out.println(\"Generated product image background response below:\");\n System.out.println(response);\n } catch (Exception e) {\n System.out.println(\"An error has occurred: \");\n System.out.println(e);\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n // Replace with your image URI.\n String imageUri =\n \"https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg\";\n generateProductImageBackground(config, imageUri);\n }\n }\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/productstudio/v1alpha/GenerateProductImageBackgroundSample.java\n\n### Python\n\n # -*- coding: utf-8 -*-\n # Copyright 2025 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \"\"\"This class demonstrates how to create product images with generated backgrounds.\"\"\"\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_productstudio_v1alpha import GenerateImageBackgroundConfig\n from google.shopping.merchant_productstudio_v1alpha import GenerateProductImageBackgroundRequest\n from google.shopping.merchant_productstudio_v1alpha import ImageServiceClient\n from google.shopping.merchant_productstudio_v1alpha import InputImage\n from google.shopping.merchant_productstudio_v1alpha import OutputImageConfig\n\n\n # Gets the merchant account ID from the user's configuration.\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n # The name of the account to which the request is sent.\n # Format: accounts/{account}\n _NAME = f\"accounts/{_ACCOUNT}\"\n\n\n def generate_product_image_background(image_uri: str) -\u003e None:\n \"\"\"Generates a product image with a custom background.\n\n Args:\n image_uri: The URI of the input image.\n \"\"\"\n # Gets OAuth Credentials.\n credentials = generate_user_credentials.main()\n\n # Creates a client.\n client = ImageServiceClient(credentials=credentials)\n\n # Creates the output config.\n # Set `return_image_uri` to False to return the image bytes in the response.\n output_config = OutputImageConfig(return_image_uri=True)\n\n # Creates the input image.\n # You can also use image bytes here instead of a URI.\n input_image = InputImage(image_uri=image_uri)\n\n # Creates the generate image background config.\n generate_image_background_config = GenerateImageBackgroundConfig(\n product_description=\"a jar\",\n background_description=(\n \"sitting on a cracked stone surface surrounded by a cherry blossom\"\n \" tree and pink and white flowers in the background, high\"\n \" resolution, product photography, strong shadows and lights,\"\n \" creative\"\n ),\n )\n\n # Creates the request.\n request = GenerateProductImageBackgroundRequest(\n name=_NAME,\n output_config=output_config,\n input_image=input_image,\n config=generate_image_background_config,\n )\n\n # Makes the request and catches and prints any error messages.\n try:\n print(f\"Sending GenerateProductImageBackground request: {_NAME}\")\n response = client.generate_product_image_background(request=request)\n print(\"Generated product image background response below:\")\n print(response)\n except RuntimeError as e:\n print(\"Request failed.\")\n print(e)\n\n\n if __name__ == \"__main__\":\n # The URI of the image to use as the base for the generation.\n # Replace with your image URI.\n _IMAGE_URI = (\n \"https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg\"\n )\n generate_product_image_background(_IMAGE_URI)\n\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/productstudio/v1alpha/generate_product_image_background_sample.py"]]