pythonpy-shiny

Display image using shiny in python


I want to display an image using Shiny in Python, but I cannot find an error in the code. The file is not uploaded once I open the app and input the image.

Here is the code:

from pathlib import Path
from shiny import render
from shiny.express import input, ui
from shiny import App, Inputs, Outputs, Session, reactive, render, ui
from shiny.types import FileInfo

ui.page_fluid(
    ui.input_file("file_input", "Upload Image"),  # Add file input
    ui.output_image("image")  
)

@render.image  
def image():
    img = {"src": input.file_input(), "width": "100px"}  
    return img

That I can display the image.


Solution

  • Looks like you're missing some stuff, like initializing the shiny App, defining properly the layout of the page and some minor syntax issues.

    Try this:

    from shiny import App, render, ui
    from shiny.types import FileInfo
    
    app = App()
    
    @app.page_fluid
    def page():
        input_file = ui.input_file("file_input", "Upload Image")
        output_image = ui.output_image("image")
    
        return [input_file, output_image]
    
    @app.render.image
    def render_image():
        img_src = input.file_input()
        img_width = "100px"
        return {"src": img_src, "width": img_width}
    
    if __name__ == "__main__":
        app.run(debug=True)