Skip to main content

Show an image

New in v13.7.0

ImageView and ImageAndDataView as replacement for the specific image views.

Currently, the following image types are supported:

  • PNG
  • JPG
  • SVG
  • GIF (>= v13.7.0)

Implementation

The easiest way to show an image in the ImageView is by using a static file:

  1. Add an image to your app repository.

    my-app
    ├── app.py
    ├── image.png
    └── ...
  2. Create a view method on the controller decorated with ImageView which returns an ImageResult:

    from pathlib import Path
    from viktor.views import ImageView, ImageResult

    class Controller(ViktorController):
    ...

    @ImageView("Image", duration_guess=1)
    def create_img_result(self, params, **kwargs):
    image_path = Path(__file__).parent / 'image.png'
    return ImageResult.from_path(image_path)

The image can also be dynamically created, for example using Matplitlib, svgwrite, drawSvg, etc. An example of Matplotlib is shown below:

import matplotlib.pyplot as plt
import numpy as np
from io import StringIO
from viktor.views import ImageView, ImageResult

class Controller(ViktorController):
...

@ImageView("Plot", duration_guess=1)
def create_result(self, params, **kwargs):
# initialize figure
fig = plt.figure()

# create plot data
x = np.random.randn(10)
plt.plot(x)

# save figure
svg_data = StringIO()
fig.savefig(svg_data, format='svg')
plt.close()

return ImageResult(svg_data)

The ImageView is only suitable for static visualizations. See WebView if interactivity is desired.

An image view can be combined with data using an ImageAndDataView.

Testing

New in v13.3.0

mock_View decorator for easier testing of view methods

Methods decorated with @ImageView, @ImageAndDataView, @PNGView, @PNGAndDataView, @JPGView, @JPGAndDataView, @SVGView, or @SVGAndDataView need to be mocked within the context of (automated) testing.

import unittest

from viktor.testing import mock_View

from app.my_entity_type.controller import MyEntityTypeController

class TestMyEntityTypeController(unittest.TestCase):

@mock_View(MyEntityTypeController)
def test_img_view(self):
params = ...
result = MyEntityTypeController().img_view(params=params)
self.assertEqual(result.image.getvalue(), ...)