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 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!

Image for post

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store