50

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?

Alex
  • 43,191
  • 44
  • 96
  • 127

15 Answers15

79

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.

Andrew
  • 3,825
  • 4
  • 30
  • 44
Steven Kryskalla
  • 14,179
  • 2
  • 40
  • 42
  • 1
    It gives an error "no images found in "file:///tmp/tmp...PNG" – Röyal Nov 12 '20 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 08 '21 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.

Wernight
  • 36,122
  • 25
  • 118
  • 131
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')
Unknown
  • 45,913
  • 27
  • 138
  • 182
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)

Community
  • 1
  • 1
Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196
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.

Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • 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 '09 at 03:45
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.

Grey Panther
  • 12,870
  • 6
  • 46
  • 64
Ivan Kvolik
  • 401
  • 6
  • 16
6

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

anthony
  • 40,424
  • 5
  • 55
  • 128
  • 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 '09 at 03:56
  • I think this is pretty neat, lateral thinking. It only works with absolute paths though. – GreenAsJade Jun 25 '14 at 07: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. – multigoodverse Jul 27 '15 at 09: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. – Finn Årup Nielsen Nov 18 '15 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.

lunix
  • 151
  • 1
  • 14
codymanix
  • 28,510
  • 21
  • 92
  • 151
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"))
Sarah Grogan
  • 117
  • 1
  • 9
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
mathandy
  • 1,892
  • 25
  • 32
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)

sujay simha
  • 99
  • 2
  • 7
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

lunix
  • 151
  • 1
  • 14
0

2022:

import os

os.open("filename.png")

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

fsevenm
  • 791
  • 8
  • 19
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()}")
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435