51

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?

15 Answers 15

81

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.

2
  • 1
    It gives an error "no images found in "file:///tmp/tmp...PNG"
    – Röyal
    Nov 12, 2020 at 12:26
  • 2
    @Röyal This is because PIL.Image.show() is intended to be a debugging tool. To use this, you need to have xz or paint installed for Linux or Windows, respectively. You will also encounter this error if you show an image, leave it open, and show another image.
    – Onofog
    Feb 8, 2021 at 22:49
12

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.

11

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')
1
  • 8
    subprocess is preferred to os.system in Python 2.4 and later. Sep 12, 2009 at 4:01
8

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.

1
  • This solution is Windows specific (namely for cmd.exe as a shell) It won't work on common *nix shells in default configuration e.g., sh, bash, etc.
    – jfs
    Sep 12, 2009 at 3:45
8

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)

7

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.

0
6

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

4
  • 1
    Indeed, webbrowser.open() works perfectly for any file type you can open from browser: images, video, office documents, mp3, etc (it starts corresponding program e.g., MPlayer for video files).
    – jfs
    Sep 12, 2009 at 3:56
  • I think this is pretty neat, lateral thinking. It only works with absolute paths though. Jun 25, 2014 at 7:41
  • I was expecting that webbrowser.open("Figure.png") would open the figure via my default internet browser. Instead, the figure was opened via the default image viewer. Do you know why? I am on Windows. Jul 27, 2015 at 9:44
  • 1
    webbrowser has the webbrowser._tryorder which contains the order of programs it will try. On my computer it has ['xdg-open', 'gvfs-open', ... , so the xdg-open program is called first. And that program further calls eog on my computer. Nov 18, 2015 at 14:06
5

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.

1
  • 1
    This doesn't answer the question though.
    – jonathan
    Feb 25, 2019 at 16:58
3

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"))
2

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
1

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)

0

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()
0

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

0

2022:

import os

os.open("filename.png")

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

1
  • This does nothing visible on Windows 10 with Python 3.7.9
    – Charles
    Dec 8 at 9:31
0

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()}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.