How to remove transparency from an image in Python
Sometimes image transparency can be undesirable, and so today we are looking into how to implement functionality to remove it entirely. If we were to set this up by hand, we would need to first set up automatic format detection, then image rendering, add support for layers, and well you get the idea. It’s going to take some serious effort for what should be a really simple action. So why don’t we just keep things really simple? Well, here’s an API that will do just that.
Our API will need its client installed, as below:
pip install cloudmersive-image-api-client
Next we shall create our function call for edit_remove_transparency, which will use this code block here.
from __future__ import print_functionimport timeimport cloudmersive_image_api_clientfrom cloudmersive_image_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_image_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_image_api_client.EditApi(cloudmersive_image_api_client.ApiClient(configuration))image_file = '/path/to/file' # file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try:# Remove transparency from the imageapi_response = api_instance.edit_remove_transparency(image_file)pprint(api_response)except ApiException as e:print("Exception when calling EditApi->edit_remove_transparency: %s\n" % e)
So if we now give it an image_file, the API will render it in the original format over a white background layer, save it, and return it to us as a download URL. Simple!