Home > Software design >  Using python bytes with winrt
Using python bytes with winrt

Time:11-27

I'm attempting to use BitmapDecoder from the winrt package with bytes I've read from a file with python.

I can do it if I use winrt to read the bytes from the file:

import os 

from winrt.windows.storage import StorageFile, FileAccessMode
from winrt.windows.graphics.imaging import BitmapDecoder

async def process_image(path):
    # get image from disk
    file = await StorageFile.get_file_from_path_async(os.fspath(path))
    stream = await file.open_async(FileAccessMode.READ)
    decoder = await BitmapDecoder.create_async(stream)
    return await decoder.get_software_bitmap_async()

The problem is that I'd really like to use the bytes in python-land before sending them to BitmapDecoder instead of getting them with StorageFile.

Browsing the MS docs, I see there's an InMemoryRandomAccessStream, which sounds like what I want, but I can't seem to get that working. I tried this:

from winrt.windows.storage.streams import InMemoryRandomAccessStream, DataWriter
stream = InMemoryRandomAccessStream()
writer = DataWriter(stream)
await writer.write_bytes(bytes_)

That gives me RuntimeError: The parameter is incorrect. for the await writer.write_bytes(bytes_) line.

Not sure what to try next.

CodePudding user response:

To use python bytes you do the following. The key was writer.write_bytes is not async and calling writer.store_async().

async def process_image(bytes_):
    stream = InMemoryRandomAccessStream()
    writer = DataWriter(stream)
    writer.write_bytes(bytes_)
    writer.store_async()
    stream.seek(0)

    decoder = await BitmapDecoder.create_async(stream)
    return await decoder.get_software_bitmap_async()
  • Related