cytoscape save graph as image by button
Asked Answered
P

3

9

I saw in the cytoscape.js tutorial that there are ways to represent the graph as image (png, jpg), but there is a way to represent it as regular graph, and if the user would want he can save it as image by click on button or similar option?

Didn't find simple way for that.

I am using python flask as my server side and cytoscape js for the graphes.

Panathenaea answered 26/8, 2016 at 14:41 Comment(0)
F
13

You don't need server side code to save files from the browser anymore.

You can save files using the saveAs() API in JS. Here's a polyfill: https://github.com/eligrey/FileSaver.js/

If you want the graph data, it would just be

var jsonBlob = new Blob([ JSON.stringify( cy.json() ) ], { type: 'application/javascript;charset=utf-8' });

saveAs( jsonBlob, 'graph.json' );

Or for images

var b64key = 'base64,';
var b64 = cy.png().substring( content.indexOf(b64key) + b64key.length );
var imgBlob = base64ToBlob( b64, 'image/png' );

saveAs( imgBlob, 'graph.png' );

(Refer to other question re. base64toBlob())

Furred answered 26/8, 2016 at 19:22 Comment(2)
Thank, its work with tiny change, i replace the scondeline with this: 'var b64 = cy.png().substring( cy.png().indexOf(b64key) + b64key.length );' i.e before this little change the "content" was not define and it throw error.Panathenaea
For more info, you can export as jpg, png, or json with numerous options: js.cytoscape.org/#core/exportBedbug
A
3

Improving the answer marked as correct:

You can use saveAs() directly, simply do:

import { saveAs } from "file-saver"; //or require
...
saveAs(cy.png(), "graph.png");

No need to handle blob content, same goes for .jpg()

Adorne answered 26/4, 2020 at 14:57 Comment(2)
Thank you. This should be included in "marked as correct"Rittenhouse
npmjs.com/package/file-saverRittenhouse
A
0

If you want a solution without further library usage, here an idea:

const pngBlob = await cy.png({
  output: 'blob-promise',
});

const fileName = 'myfile.png';
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(pngBlob);
downloadLink.download = fileName;
downloadLink.click();

Note that the output property of the png() function parameter can be used to directly generate a Blob object. If you use the value blob-promise the function returns a promise instead of a blog directly, so you can keep your UI non-blocking.

See the official cytoscape docs for more details.

Aunt answered 7/12, 2022 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.