generateImage() - Generate Image from Structure

Q

How to generate image from a given chemical structure with the ketcher.generateImage() method?

✍: FYIcenter.com

A

If you want to generate an image from the chemical structure in the Ketcher editor, you can export the structure in a specific format using a get*() method. Then call the ketcher.generateImage(structure, opts) method generate an image from the structure.

You can specify the image format like PNG, SVG, etc. and other options in the second argument of the generateImage() call.

Note that the generateImage() method returns a "blob" object in a promise. You can use the URL.createObjectURL(blob) to convert it directly to the data URL format of "data:{mime};base64,{base64_encoded_data}".

Here is an HTML document that shows you how to generate images from the structure in Ketcher editor:

<html>
<!-- generate-image-from-given-structure.html Copyright (c) FYIcenter.com. -->
<head>
<title>Generate Image from Chemical Structure</title>
</head>
<body>
<p>Create a chemical structure, then click generate buttons below the editor:</p>
<iframe id=frmKetcher src="/ketcher/index.html"
  style="width: 680px; height: 400px;"></iframe>

<p><button onclick="imageBySMILES();">Generate Image from SMILES Format</button></p>
<p><button onclick="imageByFetcher();">Generate Image from Ketcher Format</button></p>
<p>Output:</p>
<img id=output />

<script>
  var ketcher = null;
  var display = document.getElementById("output");
  const format = "png"; // or "svg"

function imageBySMILES() {
  let frm = document.getElementById("frmKetcher");
  ketcher = frm.contentWindow.ketcher;
  display.innerHTML = "";
  let promise = ketcher.getSmiles();
  outputImage(promise);
}

function imageByFetcher() {
  let frm = document.getElementById("frmKetcher");
  ketcher = frm.contentWindow.ketcher;
  display.innerHTML = "";
  let promise = ketcher.getKet();
  outputImage(promise);
}

function outputImage(promise) {
  promise = promise.then(
    function(value) {
      let opts = {outputFormat: format, backgroundColor: "255, 255, 255"};
      return ketcher.generateImage(value, opts);
    },
    function(error) {
      window.alert(error);
    }
  );

  promise.then(
    function(value) {
      display.src  = URL.createObjectURL(value);
    },
    function(error) {
      window.alert(error);
    }
  );
}
</script>
</body>
</html>

Open the above HTML document on your local Web server. Draw a simple molecule or reaction in the editor.

Click "Generate Image from SMILES Format" or "Generate Image from Ketcher Format" button, you will see that an image of the molecule or reaction is displayed.

Generate Image from Chemical Structure
Generate Image from Chemical Structure

 

Save Structure from Ketcher to Server

Call getInchi() and generateInchIKey() Methods

Ketcher JavaScript API

⇑⇑ Ketcher - Chemical Structure Editor

2023-12-14, 777🔥, 0💬