Create an image view
This guide explains how to create different types of image visualizations. Currently, the following types are supported:
- PNG
- JPG
- SVG
PNGView
Add a PNG image to your app repository.
my-app
├── app.py
├── image.png
└── ...Create a view method on the controller which returns a
PNGResult
:from pathlib import Pathfrom viktor.views import PNGResultclass Controller(ViktorController): ... @PNGView("PNG image", duration_guess=1) def create_png_result(self, params, **kwargs): png_path = Path(__file__).parent / 'image.png' return PNGResult.from_path(png_path)
In the example above, a static file is used for the visualization. However, in some cases the PNG can be obtained dynamically by other means, for example through Matplotlib or via external API's:
@PNGView("PNG image", duration_guess=1)
def create_png_result(self, params, **kwargs):
...
image = generateImageDynamically(...) # get image as BytesIO
return PNGResult(image)
A PNG view can be combined with a data view using a
PNGAndDataView
JPGView
See implementation steps of PNGView
. Make sure to use a JPGView
, which returns a
JPGResult
.
A JPG view can be combined with a data view using a
JPGAndDataView
SVGView
The svg data that has to be presented in the interface can be created in different ways. A popular way of creating plots is by using Matplotlib, of which a very small example is shown below.
Create a figure in "svg" format (can be done with Matplotlib, svgwrite, drawSvg, etc.).
Create a view method on the controller which returns a
SVGResult
:import matplotlib.pyplot as pltimport numpy as npfrom io import StringIOfrom viktor.views import SVGViewclass Controller(ViktorController): ... @SVGView("SVG plot", duration_guess=1) def create_svg_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 SVGResult(svg_data)
It is also possible to generate an SVG view from a static file:
return SVGResult.from_path(svg_file_path)
The SVGView is only suitable for static visualizations. See the WebView guide if interactivity is desired.
An SVG view can be combined with a data view using a
SVGAndDataView
Testing
New in v13.3.0
Methods decorated with @PNGView
, @PNGAndDataView
, @JPGView
, @JPGAndDataView
, @SVGView
, or @SVGAndDataView
need to be mocked within the context of (automated) testing.
import unittestfrom viktor.testing import mock_Viewfrom app.my_entity_type.controller import MyEntityTypeControllerclass TestMyEntityTypeController(unittest.TestCase): @mock_View(MyEntityTypeController) def test_png_view(self): params = ... result = MyEntityTypeController().png_view(params=params) self.assertEqual(result.image.getvalue(), ...)