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
    import viktor as vkt


    class Controller(vkt.Controller):

    @vkt.ImageView("Image")
    def create_img_result(self, params, **kwargs):
    image_path = Path(__file__).parent / 'image.png'
    return vkt.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
import viktor as vkt
from io import StringIO


class Controller(vkt.Controller):

@vkt.ImageView("Plot")
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 vkt.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(), ...)