1

I have a .net library which creates an image. I need access to this image in python so I'm trying to use pythonnet to call the .net DLL.

I'm trying to use the following answer to convert the .NET bytes: and then create the PIL.Image:

Convert Bytes[] to Python Bytes Using PythonNet PIL: Convert Bytearray to Image

Here is my python code:

import clr
preloadingiterator = clr.AddReference(r"C:\Users\Ian\source\repos\PreloadingIterator\PreloadingIterator\bin\Debug\net48\PreloadingIterator.dll")
from PreloadingIterator import ImageIterator, ImageBytesIterator, FileBytesIterator
from pathlib import Path
import io
from PIL import Image


class FileBytesIteratorWrapper():

    def __init__(self, paths):
        self.paths = paths
        self.iterator = FileBytesIterator(paths)

    def __iter__(self):
        for netbytes in self.iterator:
            pythonbytes = bytes(netbytes)
            numBytes = len(pythonbytes)
            image = Image.frombytes('RGB', (1920, 1080), pythonbytes)
            yield image

This errors with:

ValueError: not enough image data

I assumed this was because I'm returning the PNG encoded bytes, not raw, so I changed my code like this:

image = Image.frombytes('RGB', (1920, 1080), pythonbytes, decoder_name='png')

Which errors with:

'OSError: decoder png not available'

How can I return image data from .NET and decode it into a PIL Image?

Ian Newson
  • 7,679
  • 2
  • 47
  • 80

1 Answers1

1

Returning a raw image from .NET worked with this python:

def __iter__(self):
    for netbytes in self.iterator:
        pythonbytes = bytes(netbytes)
        image = Image.frombytes('RGB', (1920, 1080), pythonbytes)
        yield image

However, the speed of this was prohibitive, as the pythonnet was taking 1.3 seconds per image, and 0.07s in either python or .net natively.

Therefore I stopped using pythonnet and rewrote it to a TCP client/server architecture.

Ian Newson
  • 7,679
  • 2
  • 47
  • 80