Stay organized with collections
Save and categorize content based on your preferences.
Merchant API code sample to remove product image background.
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.packageshopping.merchant.samples.productstudio.v1alpha;importcom.google.api.gax.core.FixedCredentialsProvider;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.shopping.merchant.productstudio.v1alpha.ImageServiceClient;importcom.google.shopping.merchant.productstudio.v1alpha.ImageServiceSettings;importcom.google.shopping.merchant.productstudio.v1alpha.InputImage;importcom.google.shopping.merchant.productstudio.v1alpha.OutputImageConfig;importcom.google.shopping.merchant.productstudio.v1alpha.RemoveImageBackgroundConfig;importcom.google.shopping.merchant.productstudio.v1alpha.RemoveProductImageBackgroundRequest;importcom.google.shopping.merchant.productstudio.v1alpha.RemoveProductImageBackgroundResponse;importcom.google.shopping.merchant.productstudio.v1alpha.RgbColor;importshopping.merchant.samples.utils.Authenticator;importshopping.merchant.samples.utils.Config;/** This class demonstrates how to create product images with the background removed. */publicclassRemoveProductImageBackgroundSample{privatestaticStringgetName(StringaccountId){returnString.format("accounts/%s",accountId);}publicstaticvoidremoveProductImageBackground(Configconfig,StringimageUri)throwsException{// Obtains OAuth token based on the user's configuration.GoogleCredentialscredential=newAuthenticator().authenticate();ImageServiceSettingsimageServiceSettings=ImageServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();Stringname=getName(config.getAccountId().toString());// Calls the API and catches and prints any network failures/errors.try(ImageServiceClientimageServiceClient=ImageServiceClient.create(imageServiceSettings)){OutputImageConfigoutputImageConfig=// Set this field to false to return the image bytes in the response instead.OutputImageConfig.newBuilder().setReturnImageUri(true).build();InputImageinputImage=InputImage.newBuilder()// You can also use image bytes here instead of a URI..setImageUri(imageUri).build();RemoveImageBackgroundConfigremoveImageBackgroundConfig=RemoveImageBackgroundConfig.newBuilder()// Setting the background color to green. Don't set this field if you want the image// to have a RGBA 4-channel transparent image as the background..setBackgroundColor(RgbColor.newBuilder().setRed(0).setGreen(255).setBlue(0)).build();RemoveProductImageBackgroundRequestrequest=RemoveProductImageBackgroundRequest.newBuilder().setName(name).setOutputConfig(outputImageConfig).setInputImage(inputImage).setConfig(removeImageBackgroundConfig).build();System.out.println("Sending RemoveProductImageBackground request: "+name);RemoveProductImageBackgroundResponseresponse=imageServiceClient.removeProductImageBackground(request);System.out.println("Removed product image background response below:");System.out.println(response);}catch(Exceptione){System.out.println("An error has occurred: ");System.out.println(e);}}publicstaticvoidmain(String[]args)throwsException{Configconfig=Config.load();// Replace with your image URI.StringimageUri="https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg";removeProductImageBackground(config,imageUri);}}
# -*- 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 the background removed."""fromexamples.authenticationimportconfigurationfromexamples.authenticationimportgenerate_user_credentialsfromgoogle.shopping.merchant_productstudio_v1alphaimportImageServiceClientfromgoogle.shopping.merchant_productstudio_v1alphaimportInputImagefromgoogle.shopping.merchant_productstudio_v1alphaimportOutputImageConfigfromgoogle.shopping.merchant_productstudio_v1alphaimportRemoveImageBackgroundConfigfromgoogle.shopping.merchant_productstudio_v1alphaimportRemoveProductImageBackgroundRequestfromgoogle.shopping.merchant_productstudio_v1alphaimportRgbColor# 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}"defremove_product_image_background(image_uri:str)-> None:"""Removes the background from a product image. 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 remove image background config.# Setting the background color to green. Don't set this field if you want the# image to have a RGBA 4-channel transparent image as the background.remove_image_background_config=RemoveImageBackgroundConfig(background_color=RgbColor(red=0,green=255,blue=0))# Creates the request.request=RemoveProductImageBackgroundRequest(name=_NAME,output_config=output_config,input_image=input_image,config=remove_image_background_config,)# Makes the request and catches and prints any error messages.try:print(f"Sending RemoveProductImageBackground request: {_NAME}")response=client.remove_product_image_background(request=request)print("Removed product image background response below:")print(response)exceptRuntimeErrorase:print("Request failed.")print(e)if__name__=="__main__":# The URI of the image to remove the background from.# Replace with your image URI._IMAGE_URI=("https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg")remove_product_image_background(_IMAGE_URI)
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-13 UTC."],[],[],null,["# Remove product image background\n\nMerchant API code sample to remove 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.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 com.google.shopping.merchant.productstudio.v1alpha.RemoveImageBackgroundConfig;\n import com.google.shopping.merchant.productstudio.v1alpha.RemoveProductImageBackgroundRequest;\n import com.google.shopping.merchant.productstudio.v1alpha.RemoveProductImageBackgroundResponse;\n import com.google.shopping.merchant.productstudio.v1alpha.RgbColor;\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 the background removed. */\n public class RemoveProductImageBackgroundSample {\n\n private static String getName(String accountId) {\n return String.format(\"accounts/%s\", accountId);\n }\n\n public static void removeProductImageBackground(Config config, String imageUri) 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 RemoveImageBackgroundConfig removeImageBackgroundConfig =\n RemoveImageBackgroundConfig.newBuilder()\n // Setting the background color to green. Don't set this field if you want the image\n // to have a RGBA 4-channel transparent image as the background.\n .setBackgroundColor(RgbColor.newBuilder().setRed(0).setGreen(255).setBlue(0))\n .build();\n\n RemoveProductImageBackgroundRequest request =\n RemoveProductImageBackgroundRequest.newBuilder()\n .setName(name)\n .setOutputConfig(outputImageConfig)\n .setInputImage(inputImage)\n .setConfig(removeImageBackgroundConfig)\n .build();\n\n System.out.println(\"Sending RemoveProductImageBackground request: \" + name);\n RemoveProductImageBackgroundResponse response =\n imageServiceClient.removeProductImageBackground(request);\n System.out.println(\"Removed 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 removeProductImageBackground(config, imageUri);\n }\n }\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/productstudio/v1alpha/RemoveProductImageBackgroundSample.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 the background removed.\"\"\"\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\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 from google.shopping.merchant_productstudio_v1alpha import RemoveImageBackgroundConfig\n from google.shopping.merchant_productstudio_v1alpha import RemoveProductImageBackgroundRequest\n from google.shopping.merchant_productstudio_v1alpha import RgbColor\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 remove_product_image_background(image_uri: str) -\u003e None:\n \"\"\"Removes the background from a product image.\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 remove image background config.\n # Setting the background color to green. Don't set this field if you want the\n # image to have a RGBA 4-channel transparent image as the background.\n remove_image_background_config = RemoveImageBackgroundConfig(\n background_color=RgbColor(red=0, green=255, blue=0)\n )\n\n # Creates the request.\n request = RemoveProductImageBackgroundRequest(\n name=_NAME,\n output_config=output_config,\n input_image=input_image,\n config=remove_image_background_config,\n )\n\n # Makes the request and catches and prints any error messages.\n try:\n print(f\"Sending RemoveProductImageBackground request: {_NAME}\")\n response = client.remove_product_image_background(request=request)\n print(\"Removed 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 remove the background from.\n # Replace with your image URI.\n _IMAGE_URI = (\n \"https://services.google.com/fh/files/misc/abundance_intention_bath_salts.jpg\"\n )\n remove_product_image_background(_IMAGE_URI)\n\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/productstudio/v1alpha/remove_product_image_background_sample.py"]]