Alex
Alex

Reputation: 44709

Showing an image from console in Python

What is the easiest way to show a .jpg or .gif image from Python console?

I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?

Upvotes: 52

Views: 237934

Answers (15)

fsevenm
fsevenm

Reputation: 949

2022:

Tested on Ubuntu.

import os

os.open("filename.png")

It will open the filename.png in a window using default image viewer.

Upvotes: 0

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83788

The easiest way to display an image from a console script is to open it in a web browser using webbrowser standard library module.

  • No additional packages need to be installed

  • Works across different operating systems

  • On macOS, webbrowser directly opens Preview app if you pass it an image file

Here is an example, tested on macOS.

    import webbrowser

    # Generate PNG file
    path = Path("/tmp/test-image.png")
    with open(path, "wb") as out:
        out.write(png_data)

    # Test the image on a local screen
    # using a web browser.
    # Path URL format may vary across different operating systems,
    # consult Python manual for details.
    webbrowser.open(f"file://{path.as_posix()}")

Upvotes: 0

codymanix
codymanix

Reputation: 29468

You cannot display images in a console window. You need a graphical toolkit such as Tkinter, PyGTK, PyQt, PyKDE, wxPython, PyObjC, or PyFLTK. There are plenty of tutorials on how to create simple windows and loading images in python.

Upvotes: 5

lunix
lunix

Reputation: 361

Displaying images in console using Python

For this you will need a library called ascii_magic

Installation : pip install ascii_magic

Sample Code :

import ascii_magic

img = ascii_magic.from_image_file("Image.png")
result = ascii_magic.to_terminal(img)

Reference : Ascii_Magic

Upvotes: 0

Ariel Assayag
Ariel Assayag

Reputation: 1

You can use the following code:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
img = mpimg.imread('FILEPATH/FILENAME.jpg')
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()

Upvotes: 0

sujay simha
sujay simha

Reputation: 139

If you want to open the image in your native image viewer, try os.startfile:

import os

os.startfile('file')

Or you could set the image as the background using a GUI library and then show it when you want to. But this way uses a lot more code and might impact the time your script takes to run. But it does allow you to customize the ui. Here's an example using wxpython:

import wx
 
########################################################################
class MainPanel(wx.Panel):
    """"""
 
    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Was wx.BG_STYLE_CUSTOM)
        self.frame = parent
 
        sizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)
 
        for num in range(4):
            label = "Button %s" % num
            btn = wx.Button(self, label=label)
            sizer.Add(btn, 0, wx.ALL, 5)
        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(sizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75)
        self.SetSizer(hSizer)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
 
    #----------------------------------------------------------------------
    def OnEraseBackground(self, evt):
        """
        Add a picture to the background
        """
        # yanked from ColourDB.py
        dc = evt.GetDC()
 
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("file")
        dc.DrawBitmap(bmp, 0, 0)
 
 
########################################################################
class MainFrame(wx.Frame):
    """"""
 
    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, size=(600,450))
        panel = MainPanel(self)        
        self.Center()
 
########################################################################
class Main(wx.App):
    """"""
 
    #----------------------------------------------------------------------
    def __init__(self, redirect=False, filename=None):
        """Constructor"""
        wx.App.__init__(self, redirect, filename)
        dlg = MainFrame()
        dlg.Show()
 
#----------------------------------------------------------------------
if __name__ == "__main__":
    app = Main()
    app.MainLoop()

(source code from how to put a image as a background in wxpython)

You can even show the image in your terminal using timg:

import timg

obj = timg.Renderer()                                                                                               
obj.load_image_from_file("file")
obj.render(timg.SixelMethod)

(PyPI: https://pypi.org/project/timg)

Upvotes: 1

Steven Kryskalla
Steven Kryskalla

Reputation: 14649

Using the awesome Pillow library:

>>> from PIL import Image                                                                                
>>> img = Image.open('test.png')
>>> img.show() 

This will open the image in your default image viewer.

Upvotes: 83

Sarah Grogan
Sarah Grogan

Reputation: 137

You can also using the Python module Ipython, which in addition to displaying an image in the Spyder console can embed images in Jupyter notebook. In Spyder, the image will be displayed in full size, not scaled to fit the console.

from IPython.display import Image, display
display(Image(filename="mypic.png"))

Upvotes: 3

Ivan Kvolik
Ivan Kvolik

Reputation: 431

If you would like to show it in a new window, you could use Tkinter + PIL library, like so:

import tkinter as tk
from PIL import ImageTk, Image

def show_imge(path):
    image_window = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(image_window, image=img)
    panel.pack(side="bottom", fill="both", expand="yes")
    image_window.mainloop()

This is a modified example that can be found all over the web.

Upvotes: 7

mathandy
mathandy

Reputation: 2010

I made a simple tool that will display an image given a filename or image object or url.
It's crude, but it'll do in a hurry.

Installation:

 $ pip install simple-imshow

Usage:

from simshow import simshow
simshow('some_local_file.jpg')  # display from local file
simshow('http://mathandy.com/escher_sphere.png')  # display from url

Upvotes: 2

Wernight
Wernight

Reputation: 37600

In a new window using Pillow/PIL

Install Pillow (or PIL), e.g.:

$ pip install pillow

Now you can

from PIL import Image
with Image.open('path/to/file.jpg') as img:
    img.show()

Using native apps

Other common alternatives include running xdg-open or starting the browser with the image path:

import webbrowser
webbrowser.open('path/to/file.jpg')

Inline a Linux console

If you really want to show the image inline in the console and not as a new window, you may do that but only in a Linux console using fbi see ask Ubuntu or else use ASCII-art like CACA.

Upvotes: 12

Janus Troelsen
Janus Troelsen

Reputation: 21270

In Xterm-compatible terminals, you can show the image directly in the terminal. See my answer to "PPM image to ASCII art in Python"

ImageMagick's "logo:" image in Xterm (show picture in new tab for full size viewing)

Upvotes: 8

Unknown
Unknown

Reputation: 46773

Since you are probably running Windows (from looking at your tags), this would be the easiest way to open and show an image file from the console without installing extra stuff like PIL.

import os
os.system('start pic.png')

Upvotes: 11

Jochen Ritzel
Jochen Ritzel

Reputation: 107598

Or simply execute the image through the shell, as in

import subprocess
subprocess.call([ fname ], shell=True)

and whatever program is installed to handle images will be launched.

Upvotes: 8

anthony
anthony

Reputation: 41088

Why not just display it in the user's web browser?

Upvotes: 6

Related Questions