1
votes

I want to load an image file into memory

In Delphi language there is a class named TMemoryStream that you can use to load some data to memory, how I should use something like MemoryStream in Python language ?

3
mmap module maybe? - kindall
There isn't a direct equivalent. Certainly not mmap. Rather than trying to translate literally it will be more productive to work out the idiomatic Python approach. - David Heffernan

3 Answers

4
votes

Having a quick look at TMemoryStream in the Delphi docs, it looks like the class is about producing a block of memory that is enhanced with file-like IO operators.

The equivalent class in Python can be found in the StringIO module: https://docs.python.org/2/library/stringio.html

(c)StringIO is not strictly a block of memory, as Python doesn't really expose raw memory as a concept. It can however be used to implement files in RAM, for example, creating an image file as a string for PIL (or Pillow), and then write it out to a browser as part of a CGI script. https://stackoverflow.com/a/41501060/7811466

4
votes

I don't know TMemoryStream but this is how you would read a binary file into RAM (assuming Python 3):

with open('filename', mode='rb') as infile:
    data = infile.read()
1
votes

There are many packages for image manipulation in python. One of them is PIL, here is an example:

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
%matplotlib inline     

# Loada Image
img = Image.open('debian1.png', 'r') 

# Show image:
imshow(np.asarray(img))

See a Jupyter Notebook with this code, here!