Depicting Molecule in JPG

Problem

You want to generate an image of your molecule in JPG format.

Ingredients

Note

Requires OpenEye toolkits version 2013.Feb or later.

Difficulty level

../_images/chilly2.png

Solution

The following table lists the image file formats natively supported in OEDepict TK and their associated file extensions.

Graphics File Format Format Type File Extension
PNG (Portable Network Graphics) raster image .png
SVG (Scalable Vector Graphics) vector image .svg
bare SVG (with no header) vector image .bsvg
Postscript vector image .ps
Encapsulated PostScript vector image .eps
PDF (Portable Document Format) vector image .pdf

Unfortunately, the jpg image format is not supported. However a png image generated by the OEDepict TK can be converted to jpg using the PIL python image processing library. The following python code converts the molecule.png image into molecule.jpg image file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python3
import os
import sys
try:
    from PIL import Image
except:
    print ("Please install the Python Image Library (PIL)")
    print ("from: http://www.pythonware.com/products/pil/index.htm")
    sys.exit(1)


def Convert2JPG(ifname):

    fname, ext = os.path.splitext(ifname)
    ofname = os.path.join(fname + ".jpg")
    image = Image.open(ifname)
    image.save(ofname)

Convert2JPG("molecule.png")

Discussion

You can also directly render your molecule into a JPG image file. The following function renders a molecule directly to an output file stream (oeofstream) if the image type is supported by OEDepict TK. In the case of JPG, GIF or TIFF image types, first the image is written into an output string stream (oeosstream) in PNG format. This is then converted into the appropriate image file format using the PIL image library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def RenderMolecule(mol, opts, ofilename):

    disp = OE2DMolDisplay(mol, opts)

    ext = OEGetFileExtension(ofilename)
    if OEIsRegisteredImageFile(ext):

        ofs = oeofstream()
        OERenderMolecule(ofs, ext, disp)

    elif ext in ['jpg', 'tiff', 'gif']:

        imagestr = OERenderMoleculeToString('png', disp)
        imagefile = io.BytesIO(imagestr)
        image = Image.open(imagefile)
        image.save(ofilename)

Download code

mol2img.py

Usage:

prompt > python3 mol2img.py molecule.ism molecule.jpg
prompt > python3 mol2img.py molecule.sdf molecule.png

See also

See also in OEChem manual

API

See also in OEDepict manual

Theory

API