Yes, you can! The img object returned by Chem.Draw.MolsToGridImage (when useSVG=False, which is the default) is a PIL (Pillow) Image object. PIL Image objects have a save() method.
Here's how you can do it:
python
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D # For MolDrawOptions
# --- Setup: Example data (replace with your actual data) ---
smiles_list = ['CCO', 'c1ccccc1O', 'CNC(=O)N', 'CC(=O)Oc1ccccc1C(=O)OH']
mol_list = [Chem.MolFromSmiles(s) for s in smiles_list]
label_list = [f"Molecule {i+1}" for i in range(len(mol_list))]
molsPerRow = 2
# --- Configure Drawing Options (optional, but good practice) ---
opts = rdMolDraw2D.MolDrawOptions()
opts.legendFontSize = 18 # Example: Make legend text larger
opts.useBWAtomPalette() # Example: Use black and white palette
# Add more options as needed, e.g.:
# opts.setBondLineWidth(1.5)
# opts.fixedBondLength = 30
# opts.addStereoAnnotation = True
# --- Generate the image ---
img = Chem.Draw.MolsToGridImage(
mol_list,
molsPerRow=molsPerRow,
legends=label_list,
subImgSize=(300, 300), # Increased size for clarity
drawOptions=opts
)
# --- Save the image to a file ---
output_filename_png = "molecule_grid.png"
output_filename_jpg = "molecule_grid.jpg"
output_filename_tiff = "molecule_grid.tiff"
# output_filename_svg = "molecule_grid.svg" # For SVG, see below
try:
# Save as PNG (recommended for chemical structures - lossless)
img.save(output_filename_png)
print(f"Image saved as {output_filename_png}")
# Optionally, save in other formats:
# Save as JPEG (lossy, may not be ideal for sharp lines)
# img.save(output_filename_jpg, quality=90) # quality is 0-100
# print(f"Image saved as {output_filename_jpg}")
# Save as TIFF (lossless, can be large)
# img.save(output_filename_tiff)
# print(f"Image saved as {output_filename_tiff}")
except AttributeError:
print("Error: 'img' is not a PIL Image object. This can happen if useSVG=True was used.")
print("If you used useSVG=True, 'img' is an SVG string, not a PIL Image.")
except Exception as e:
print(f"An error occurred while saving the image: {e}")
# --- To save as SVG (Scalable Vector Graphics) ---
# You need to tell MolsToGridImage to generate SVG directly.
# The returned object will be a string containing the SVG data.
try:
svg_content = Chem.Draw.MolsToGridImage(
mol_list,
molsPerRow=molsPerRow,
legends=label_list,
subImgSize=(300, 300),
drawOptions=opts,
useSVG=True # <<<< Key change for SVG output
)
output_filename_svg = "molecule_grid.svg"
with open(output_filename_svg, "w") as f_svg:
f_svg.write(svg_content)
print(f"Image saved as {output_filename_svg}")
except TypeError:
print("Error: 'svg_content' is not a string. This happens if useSVG=False (default).")
except Exception as e:
print(f"An error occurred while saving the SVG: {e}")
Explanation:
img.save(filename):
This is the standard method for PIL Image objects.
Pillow automatically determines the file format from the extension you provide in the filename (e.g., .png, .jpg, .gif, .tiff, .bmp).
PNG is generally recommended for chemical structures because it's a lossless format and handles sharp lines and text well.
JPEG is a lossy format. While it can produce smaller files, it might introduce artifacts around lines and text, which is usually not desirable for chemical drawings. If you use JPEG, you can specify the quality parameter (e.g., img.save("file.jpg", quality=95)).
TIFF is another lossless format, often used for print.
SVG Output (useSVG=True):
If you want a scalable vector graphic (SVG), you need to pass useSVG=True to MolsToGridImage.
In this case, the function does not return a PIL Image object. Instead, it returns a string containing the SVG markup.
You then save this string to a file with an .svg extension using standard file I/O (open() and write()).
Choose the method (PIL save() or direct SVG output) based on the file format you need. For most general purposes where a raster image is fine, PNG is a good choice. If you need scalability without loss of quality (e.g., for publications or web display where zooming is important), SVG is excellent.
User
take this as example. save image file. smiles_list = ['CCO', 'c1ccccc1O', 'CNC(=O)N', 'CC(=O)Oc1ccccc1C(=O)OH']
mol_list = [Chem.MolFromSmiles(s) for s in smiles_list]
Assistant
Okay, let's use your smiles_list and mol_list to generate a grid image and save it to a file.
We'll save it as a PNG, which is generally a good format for chemical structures. I'll also include an example of how to save it as an SVG if you prefer a vector format.
python
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdMolDraw2D # For MolDrawOptions
# Your provided data
smiles_list = ['CCO', 'c1ccccc1O', 'CNC(=O)N', 'CC(=O)Oc1ccccc1C(=O)OH']
mol_list = [Chem.MolFromSmiles(s) for s in smiles_list]
# --- Parameters for MolsToGridImage ---
# Create labels (legends) for each molecule (optional, but good for context)
label_list = [f"Mol {i+1}: {smiles_list[i]}" for i in range(len(mol_list))]
# label_list = [Chem.MolToSmiles(m) for m in mol_list] # Alternative: use SMILES as legends
molsPerRow = 2 # How many molecules you want in each row of the grid
subImgSize = (300, 300) # Size of the drawing area for each individual molecule
# --- Drawing Options (optional, customize as needed) ---
opts = rdMolDraw2D.MolDrawOptions()
opts.legendFontSize = 18 # Make legend text larger
opts.useBWAtomPalette() # Use black and white for atoms
# opts.setAtomPalette({1: (0,0,0), 6: (0.2,0.2,0.2), 7:(0,0,1), 8:(1,0,0)}) # Example custom palette
# opts.fixedBondLength = 30
# opts.addStereoAnnotation = True
# opts.includeAtomNumbers = True # If you want atom numbers displayed
# --- Generate the grid image (as a PIL Image object by default) ---
print("Generating PIL image...")
try:
img = Chem.Draw.MolsToGridImage(
mol_list,
molsPerRow=molsPerRow,
legends=label_list,
subImgSize=subImgSize,
drawOptions=opts,
useSVG=False # Explicitly False for PIL Image output (this is the default)
)
# --- Save the PIL Image to a file ---
output_filename_png = "molecule_grid_output.png"
output_filename_jpg = "molecule_grid_output.jpg"
if img: # Check if image generation was successful
# Save as PNG (recommended for chemical structures - lossless)
img.save(output_filename_png)
print(f"Image saved as PNG: {output_filename_png}")
# Optionally, save in other formats:
# Save as JPEG (lossy, may not be ideal for sharp lines)
# img.save(output_filename_jpg, quality=90) # quality is 0-100
# print(f"Image saved as JPG: {output_filename_jpg}")
else:
print("Error: MolsToGridImage returned None. Check your input molecules.")
except Exception as e:
print(f"An error occurred while generating or saving the PIL image: {e}")
print("Make sure you have Pillow (PIL fork) installed: pip install Pillow")
print("-" * 30)
# --- Alternative: Save as SVG (Scalable Vector Graphics) ---
print("Generating SVG image...")
try:
svg_content = Chem.Draw.MolsToGridImage(
mol_list,
molsPerRow=molsPerRow,
legends=label_list,
subImgSize=subImgSize,
drawOptions=opts,
useSVG=True # <<<< Key change for SVG output
)
output_filename_svg = "molecule_grid_output.svg"
if svg_content and isinstance(svg_content, str):
with open(output_filename_svg, "w") as f_svg:
f_svg.write(svg_content)
print(f"Image saved as SVG: {output_filename_svg}")
else:
print("Error: MolsToGridImage with useSVG=True did not return a valid SVG string.")
except Exception as e:
print(f"An error occurred while generating or saving the SVG image: {e}")
How it works:
Chem.Draw.MolsToGridImage(...):
When useSVG=False (which is the default), this function returns a PIL (Pillow) Image object.
When useSVG=True, this function returns a string containing the SVG data.
Saving PIL Image (img.save()):
The img object (which is a PIL Image) has a built-in save() method.
You provide the filename (e.g., "molecule_grid_output.png"). Pillow infers the format from the file extension.
PNG is generally preferred for line art and text like chemical structures because it's lossless.
Saving SVG (File I/O):
The svg_content string is written directly to a file using Python's standard file operations (open() and write()).
SVG files are vector-based, meaning they can be scaled to any size without losing quality, making them great for publications or web use.
After running this script, you should find molecule_grid_output.png and molecule_grid_output.svg (if that part also runs successfully) in the same directory as your Python script.