Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could the ability to add images be made a feature? #1551

Open
guiglass opened this issue Dec 24, 2024 · 4 comments
Open

Could the ability to add images be made a feature? #1551

guiglass opened this issue Dec 24, 2024 · 4 comments
Labels

Comments

@guiglass
Copy link

guiglass commented Dec 24, 2024

Hi I started using this tool thinking it was really amazing, upon realizing there is no support for local images I then started researching if there was even a single example of a way to accomplish adding a image to the gui, or any built-in way to add images. This being a tool for designing GUIs I was pretty surprised to not see this available , as it was very unexpected there is no recommended way to support image files. I was wondering if there is any plan to add built-in web server capability , or provide a example on how to use local images. I might not be able to continue using pywebview as my project requires images and icons. But hopefully in the future this will be supported or a example given that others can follow , after searching the internet I have exhausted all options, reading every post in this git and the author merely recommends a possible solution, never provides a functional example that I could find . If there is a example how to use image files with pywebview it could be really helpful!!

@guiglass
Copy link
Author

guiglass commented Dec 24, 2024

At first I was a bit intimidated that the recommended solution was to roll your own web server, but in reality it was not very difficult using Python's HTTPServer class, and the ThreadingHTTPServer class.

Now I have a elegant way to host only image/file in the local folder for my WebView on Windows, and the web server even exits when the main application closes!

Here is a minimal example showing how to launch a web server to host local images that can be accessed by the WebView:

import webview
import threading
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler

html = """
<body>
     <img src="http://localhost:8888/thumbnail_0.png">
</body>
"""

if __name__ == '__main__':

    #start the local web file server
    server = ThreadingHTTPServer(("localhost", 8888), SimpleHTTPRequestHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()

    #create the webview
    window = webview.create_window('Local Image Example', html=html)
    webview.start()

[EDIT]

Anyone using PyInstaller to compile to a application, I found when running the application the root directory was no longer pointing to the same folder as the script, where I placed the images folder in the same folder as the script, so when HTTPServer was pointing to a different root folder it caused the image links to break.

But the solution was simply to change the working directory:

import os

script_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(script_directory) #change the current working directory that CGIHTTPRequestHandler serves from to script directory.

Adding those lines before staring the server ensures the hosted folder will always point to the same folder as the .py script.

@r0x0r
Copy link
Owner

r0x0r commented Dec 31, 2024

I haven't considered an image support, but since 5.0 introduced a DOM support, not having native support for images in a serverless mode looks a bit silly indeed.
Support for images can be added, but I am not sure at this point how it should be implemented. Converting images to Base64 and loading them inline looks like the most straightforward choice, but this raises another question how images should be bundled with the app.
Suggestions and idea are welcomed.

Copy link

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@github-actions github-actions bot added the stale label Jan 31, 2025
@guiglass
Copy link
Author

guiglass commented Jan 31, 2025

Support for images can be added, but I am not sure at this point how it should be implemented. Converting images to Base64 and loading them inline looks like the most straightforward choice, but this raises another question how images should be bundled with the app. Suggestions and idea are welcomed.

@r0x0r I've had really good success using Pywebview to build a entire applications that include graphics in the UI and was all possible using the built-in ThreadingHTTPServer method mentioned above.

Image

But I forget the explain how I actually created the URL for each image. So for anyone interested it's really quite simple and doesn't require encoding data to base64. Instead what I did was to first start the ThreadingHTTPServer server, then pass the local address/port number to a Python function that calls the web API and runs a Javascript function that finds all img elements in the DOM and simply prepend each src="image.png" with the local hosted address.

As a example, first create the Python API function that generates the prepended url string, and then passes it to the javascript:

class Api:
    def bind(self, *args):
        window = args[0]
	http_address = "127.0.0.1"
	http_port = "38001"
        window.evaluate_js("initializeView({url: \"http://%s:%s/\"})" % (http_address, http_port))

Once the string has been received by the javascript it then loops through all DOM elements of type IMG and modifies their src attributes by simply prepending the url string to the existing image.png file name

<script>
    function initializeView(response) {

        var allImages = document.getElementsByTagName('img');

        for(var i = 0; i < allImages.length ; i++) {
          allImages[i].src = response.url + allImages[i].src;
        }
    }
</script>

This way the app HTML remains very simple, where each image is simply the filename (and a subfolder if the files are stored in a "images" directory).

So for my apps the images are really simple to manage, no encoding of images, it's just simple HTML and resembles plain web development, you can simply add a image element with a filename:
<img style="padding-right:0.0em;padding-top:2em; float: right;" src="images/neural_network.png">

And later Python will launch a server and instruct the javascript to modify the paths for all images in the DOM during initialization. And it seems to work great!

BTW Thank you for making pywebview possible, It has allowed me to build amazing looking and responsive GUIs that are simple to develop and has saved so much time as HTML Javascript Python is a really great combination, especially since it works with pytorch directly!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants