How to create & save a tkinter.Canvas image on a server w/ no display - python-3.x

I've written a program that generates an image via tkinter.Canvas and saves it. Now I'm updating this project to use FastAPI to let users hit my end-point and download this image.
I'm not trying to display the image on the server, just generate it in memory, save it to storage, then return that image.
Initial proof-of-concept tests work, but I cannot get this to work in Docker because no $DISPLAY is set. Unlike other questions I've seen, I'm not trying to display the image directly, just generate the image, save it, and return a file-path.
This is not a dupe of Tkinter setup on headless server. That question boils down to "how do I not run tkinter while on a server?" I still need tkinter, I just have no intention of displaying it.
I have also seen something about X11, but it seems like I'd need to know the server's environment in order to install X11, and I do not.
Is tkinter really not able to generate an image without $DISPLAY (even if I don't intend to display it)? If so, is there an alternative to tkinter I can use that can generate an image without needing a $DISPLAY? Am I totally misunderstanding a major part of how this works? It seems like I should be able to generate an image and save the bytes without needing all the things required for actual graphical rendering...

Using Pillow.Image and Pillow.ImageDraw instead of tkinter works for my scenario. (Credit goes to #acw1668)
My project only draws lines, circles, and polygons - all things that ImageDraw can do. The process of switching from one to the other was exceptionally straightforward, and Docker returns the ImageDraw/Image file with no issues!

Related

Problem with Imagemagick import (import-im6.q16) jammy/gnome

I use Imagemagick's "import" (import-im6.q16) a lot for capturing screen data. And it works great on my primary workstation using the Mate desktop.
But I am trying to use it on Jammy/Gnome and it just hangs.
Nothing in any of the obvious logs (syslog,Xorg). Searched the web and the Imagemagick communities and come up empty.
Executing import tmp.png should turn the "cross-hair" cursor on and allow selection of a region of the default X display. Upon "mouse up", the selected region is written to the file specified. An existing file will be overwritten permissions permitting. The suffix should be an image file type or errors can occur (.pdf is an example).
Can anyone confirm this is broken or working with Gnome?

Render small LaTeX-Snippets on GTK GUI using Rust

Problem
I am developing a Rust program which has a GTK3 GUI using the given rust-gtk-binding.
The program should be cross-platform (at least Linux and Windows).
The GUI should be able to show custom plaintexts and small LaTeX-snippets to allow the use math environments (small means sizes of one formula as an element to display).
Therefore, I need a way to convert LaTeX-code into something which can be displayed by the GUI.
Ideas and their problems
I can see two approaches displaying LaTeX:
Compile the LaTeX-source into pdf and then into some image type. It should be possible to use Ghostscript to get the image. But I do not know how to generate the pdf in a way which is lightweight (does not include rather large packages like miktex) and cross-platform. This option could also be overkill as there is no need to dynamically download special packages, a good math support would be sufficient. The positive side is that rendering an image in GTK should be easy.
Use KaTeX which should be sufficient for math environments. I was able to install matching crates and generate HTML source from some formulas. But here it becomes difficult to render the result as GTK has no native way for displaying HTML. As it would be difficult to integrate a HTML-engine into the GUI it would be optimal to find a tool which is able to render HTML to an image type which then can be displayed.
Now I have two ways both using an intermediate step where for common LaTeX the first step is difficult and for KaTeX the second step displays a problem. For both approaches' difficult steps I could not find any feasible solution.
Are there any libraries or similar I could not find or are there any different approaches?
It would be perfectly sufficient to be able to render a single formula, I just want to avoid such massive and difficult overkills like using a complete LaTeX compiler or half a browser to render HTML.
After searching and evaluating many more approaches I got a solution which is kind of good while also having some major drawbacks:
First of all, I use TinyTex as LaTeX environment. I did not restrict the use of LaTeX to e.g. math environments. TinyTex offers support for major platforms while being lightweight and portable. Additional LaTeX packages have to be installed manually which allows me to decide which ones are being shipped with my application.
The negative side is that while TinyTex is lightweight for a LaTeX environment it still is rather big for its purpose here (about 250MB).
I installed the required packages to use \documentclass[preview]{standalone} to get an already cropped pdf.
Afterwards I use Ghostscript to get a png-image for the generated pdf. I did not use language bindings and instead just went std::process::Command.
The following lines should be sufficient to convert test.tex into test.png with the portable TinyTex installation and Ghostscripts gswin64c.exe present in subfolders of the project's directory under Windows: (As TinyTex and Ghostscript also exist for other OS the given example can easily be changed to work on other systems)
use std::process::Command;
fn main() {
let output = Command::new("TinyTex\\bin\\win32\\pdflatex.exe")
.args(&["test.tex"])
.output()
.expect("Some error message 1");
println!("{}", String::from_utf8(output.stdout).unwrap());
let output = Command::new("gs\\gswin64c.exe")
.args(&[
"-dNOPAUSE",
"-dBATCH",
"-sDEVICE=png16m",
"-r1000",
"-sOutputFile=test.png",
"test.pdf",
])
.output()
.expect("Some error message 2");
println!("{}", String::from_utf8(output.stdout).unwrap());
}
Of course this is no particulary good and useful code at this stage but it shows how to proceed with the given problem and I wanted to leave it here in case anyone with a similar problems finds this post.

How to show images in python3

I'm a beginner and I'm having problems of showing images in python3. I would like to know what are some codes that could show images in python 3,f or a mac user. Thanx!
Do you have some more context? Where are you trying to display the image?
Your best bet is probably to open another program and give it the path to the image you want to display. To open the file ~/screenshot.png, for example, you could run
from subprocess import run
run(["open", "~/screenshot.png"])
This is pretty delicate however. It requires the user to have open installed on their computer, and for that executable to do what you expect it to do. Depending on what your usecase is, it might make more sense for you to use a graphical library to draw the image.

Batch generate height map from images

I have many many .png files and I'm looking for a way to generate height maps (or normal maps) for each of them. I can get the result I want from the gimp normalmap plugin but I need a way to automate the process or an alternative tool. I don't know enough about the underlying algorithms to reproduce them, and very little about cg in general. Is there a library or tool that will do this? I'm not picky about the language as long as the api/interface is high-level enough, though open source is preferable as I don't have access to fancy software at the moment. Thanks!
You can jsut script GIMP itself for that.
I don't know which plug-in you are calling 'normalmap' - or what you mean by 'height map' (height maps I know are just the grayscale version of the image) - but even if it is a third party plug-in, it should be possible to run it through the scripting interface.
Just go to plug-ins-> Python-FU->console - you will be dropped to a Python prompt. Click on the "browse" button - then locate the plug-on you want to call. If you click "apply" - the browser will paste a template for the plug-in call to the Python prompt.
SO, prior to doing that, you may want to test the call: open a sample image, go to the Python prompt, and get a reference to the image by typing:
image = gimp.image_list()[0], then get a reference to the first layer of the image typing drawable = image.layers[0] .
These should be all the data the call for your plug-in would need to be pre-created. Do as above to paste a call to your desired plug-in on the prompt. Note that the names image and drawable above are just variable names - you may chooseyour own - but these are the names that are usually pre-filled in when you pick "apply" from the "Browse" button for a procedure call.
Once you get it working up to here, you can leverage on Python to open all images in a folder, apply the plug-in, and save them back - you can typ e this directly on the console, or later, create a plug-in that will show up in the menus.
import os
for filename in os.listdir('mydir'):
if not filename.endswith('.png'): continue
name = 'mydir/' + filename
image = pdb.gimp_file_load(name, name)
pdb.plug_in_bump_map(......) # use your plug-in here
outputname = 'mydir/' + name.split('.')[0] + '_normal.png'
pdb.gimp_file_save(image, image.layers[0], outputname, outputname)
pdb.gimp_image_delete(image) # just frees the image from memory.
Just press twice and the sequence will be run for an entire folder.
(Note that if you want to run the "bump-map" plug-in there are several parameters that have to be replaced from variable names to the actual values you want).
If that is what you want, and you will be using it a lot, save it as a .py file, and put that code inside a proper function to turn it into a plug-in
- there is a fill examplee for that in my answer here:
GIMP: Create image stack from all image files in folder

Create PDF reports on Linux

I'm facing the following situation at moment:
I need to generate a PDF report containing some parameters and graphs. I'm running a C daemon (on Arch Linux, Raspberry PI) which receives the data and should then generate such a report. My first version was using the library libharu and simply painted everything into the PDF.
This actually worked great but it's not a damn good solution, since I have to recompile the whole daemon if I want to change the style of the generated report.
I was thinking about using some kind of template, which I can load by my code and then render into the PDF. Does anyone know a library or something I could use for that?
I'm also open for other good ideas to solve my problem :-)

Resources