Generating Transparent PNG

Problem

You want to depict your molecule in a png image with transparent background for your presentation.

Ingredients

Difficulty Level

🌶️

Solution

If you are rendering a molecule directly into an image file, all you have to do is to call the OERenderMolecule function with the clearbackground = False parameter. If this parameter is True (by default) then the OEWhite color is used to clear the image before rendering the molecule.

1def render_molecule(
2    mol: oechem.OEMolBase, opts: oedepict.OE2DMolDisplayOptions, filename: str
3) -> None:
4    """Render molecule with transparent background."""
5    disp = oedepict.OE2DMolDisplay(mol, opts)
6    clear_background = False
7    oedepict.OERenderMolecule(filename, disp, clear_background)

Discussion

In the case where you are rendering a molecule into an OEImage object, this object has to be constructed with the OETransparentColor color.

 1def render_molecule_to_image(
 2    mol: oechem.OEMolBase, opts: oedepict.OE2DMolDisplayOptions, filename: str
 3) -> None:
 4    """Render molecule to image with transparent background."""
 5    image = oedepict.OEImage(
 6        opts.GetWidth(), opts.GetHeight(), oechem.OETransparentColor
 7    )
 8
 9    disp = oedepict.OE2DMolDisplay(mol, opts)
10    clear_background = False
11    oedepict.OERenderMolecule(image, disp, clear_background)
12    oedepict.OEWriteImage(filename, image)

Note

The OEDepict TK supports transparent background for png, svg and pdf image files.

See also in OEDepict TK manual

Theory

API